github.com/JarrahG/buffalocli@v0.0.0-20230801092127-b85bfd5d395a/internal/plugins/plugins_test.go (about)

     1  package plugins
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"strings"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/gobuffalo/envy"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestAskBin_respectsTimeout(t *testing.T) {
    15  	r := require.New(t)
    16  
    17  	from, err := envy.MustGet("BUFFALO_PLUGIN_PATH")
    18  	if err != nil {
    19  		t.Skipf("BUFFALO_PLUGIN_PATH not set.")
    20  		return
    21  	}
    22  
    23  	if fileEntries, err := os.ReadDir(from); err == nil {
    24  		found := false
    25  		for _, e := range fileEntries {
    26  			if strings.HasPrefix(e.Name(), "buffalo-") {
    27  				from = e.Name()
    28  				found = true
    29  				break
    30  			}
    31  		}
    32  		if !found {
    33  			t.Skipf("no plugins found")
    34  			return
    35  		}
    36  	} else {
    37  		r.Error(err, "plugin path not able to be read")
    38  		return
    39  	}
    40  
    41  	const tooShort = time.Millisecond
    42  	impossible, cancel := context.WithTimeout(context.Background(), tooShort)
    43  	defer cancel()
    44  
    45  	done := make(chan struct{})
    46  	go func() {
    47  		askBin(impossible, from)
    48  		close(done)
    49  	}()
    50  
    51  	select {
    52  	case <-time.After(tooShort + 80*time.Millisecond):
    53  		r.Fail("did not time-out quickly enough")
    54  	case <-done:
    55  		t.Log("timed-out successfully")
    56  	}
    57  
    58  	if _, ok := findInCache(from); ok {
    59  		r.Fail("expected plugin not to be added to cache on failure, but it was in cache")
    60  	}
    61  }