...

Source file src/github.com/cli/go-gh/v2/gh_test.go

Documentation: github.com/cli/go-gh/v2

     1  package gh
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  	"os"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func TestHelperProcess(t *testing.T) {
    15  	if os.Getenv("GH_WANT_HELPER_PROCESS") != "1" {
    16  		return
    17  	}
    18  	if err := func(args []string) error {
    19  		if args[len(args)-1] == "error" {
    20  			return fmt.Errorf("process exited with error")
    21  		}
    22  		fmt.Fprintf(os.Stdout, "%v", args)
    23  		return nil
    24  	}(os.Args[3:]); err != nil {
    25  		fmt.Fprint(os.Stderr, err)
    26  		os.Exit(1)
    27  	}
    28  	os.Exit(0)
    29  }
    30  
    31  func TestHelperProcessLongRunning(t *testing.T) {
    32  	if os.Getenv("GH_WANT_HELPER_PROCESS") != "1" {
    33  		return
    34  	}
    35  	args := os.Args[3:]
    36  	fmt.Fprintf(os.Stdout, "%v", args)
    37  	fmt.Fprint(os.Stderr, "going to sleep...")
    38  	time.Sleep(10 * time.Second)
    39  	fmt.Fprint(os.Stderr, "...going to exit")
    40  	os.Exit(0)
    41  }
    42  
    43  func TestRun(t *testing.T) {
    44  	var stdout, stderr bytes.Buffer
    45  	err := run(context.TODO(), os.Args[0], []string{"GH_WANT_HELPER_PROCESS=1"}, nil, &stdout, &stderr,
    46  		[]string{"-test.run=TestHelperProcess", "--", "gh", "issue", "list"})
    47  	assert.NoError(t, err)
    48  	assert.Equal(t, "[gh issue list]", stdout.String())
    49  	assert.Equal(t, "", stderr.String())
    50  }
    51  
    52  func TestRunError(t *testing.T) {
    53  	var stdout, stderr bytes.Buffer
    54  	err := run(context.TODO(), os.Args[0], []string{"GH_WANT_HELPER_PROCESS=1"}, nil, &stdout, &stderr,
    55  		[]string{"-test.run=TestHelperProcess", "--", "gh", "error"})
    56  	assert.EqualError(t, err, "gh execution failed: exit status 1")
    57  	assert.Equal(t, "", stdout.String())
    58  	assert.Equal(t, "process exited with error", stderr.String())
    59  }
    60  
    61  func TestRunInteractiveContextCanceled(t *testing.T) {
    62  	// pass current time to ensure that deadline has already passed
    63  	ctx, cancel := context.WithDeadline(context.Background(), time.Now())
    64  	cancel()
    65  	err := run(ctx, os.Args[0], []string{"GH_WANT_HELPER_PROCESS=1"}, nil, nil, nil,
    66  		[]string{"-test.run=TestHelperProcessLongRunning", "--", "gh", "issue", "list"})
    67  	assert.EqualError(t, err, "gh execution failed: context deadline exceeded")
    68  }
    69  

View as plain text