github.com/erikwilson/go-powershell@v0.0.0-20200701182037-6845e6fcfa79/shell_test.go (about)

     1  package powershell
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/rancher/go-powershell/backend"
    10  )
    11  
    12  type context struct {
    13  	shell Shell
    14  }
    15  
    16  func TestLocalShell(t *testing.T) {
    17  	c := context{}
    18  	dir, err := ioutil.TempDir("", "pwsh-test")
    19  	if err != nil {
    20  		t.Errorf("error from TempDir: %v", err)
    21  	}
    22  	defer os.RemoveAll(dir)
    23  	f, err := ioutil.TempFile(dir, "cowabunga")
    24  	if err != nil {
    25  		t.Errorf("error from Tempfile: %v", err)
    26  	}
    27  	f.Close()
    28  	if err := os.Chdir(dir); err != nil {
    29  		t.Errorf("error from Chdir: %v", err)
    30  	}
    31  
    32  	s, err := New(&backend.Local{})
    33  	if err != nil {
    34  		t.Skip("error from New: ", err)
    35  	}
    36  
    37  	c.shell = s
    38  	t.Run("it can run commands", c.basicTest)
    39  	t.Run("it correctly parses its boundary token", c.boundaryTest)
    40  }
    41  
    42  func (c *context) basicTest(t *testing.T) {
    43  	sout, serr, err := c.shell.Execute(`echo "hi from stdout"`)
    44  	if err != nil {
    45  		t.Errorf("error from Execute: %v", err)
    46  	}
    47  
    48  	if sout != "hi from stdout\r\n" {
    49  		t.Errorf("unexpected stdout: %q", sout)
    50  	}
    51  	if serr != "" {
    52  		t.Errorf("unexpected stderr: %q", sout)
    53  	}
    54  }
    55  
    56  func (c *context) boundaryTest(t *testing.T) {
    57  	done := make(chan bool)
    58  	for i := 0; i < 1000; i++ {
    59  		timeout := time.After(10 * time.Second)
    60  
    61  		go func() {
    62  			_, _, err := c.shell.Execute("ls")
    63  			if err != nil {
    64  				t.Errorf("error from Execute: %v", err)
    65  			}
    66  			done <- true
    67  		}()
    68  
    69  		select {
    70  		case <-timeout:
    71  			t.Fatalf("Timed out waiting for command after %d iterations", i)
    72  		case <-done:
    73  			continue
    74  		}
    75  	}
    76  }