github.com/leowmjw/otto@v0.2.1-0.20160126165905-6400716cf085/plugin/plugin_test.go (about)

     1  package plugin
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"os/exec"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/hashicorp/otto/app"
    12  	pluginrpc "github.com/hashicorp/otto/rpc"
    13  )
    14  
    15  func helperProcess(s ...string) *exec.Cmd {
    16  	cs := []string{"-test.run=TestHelperProcess", "--"}
    17  	cs = append(cs, s...)
    18  	env := []string{
    19  		"GO_WANT_HELPER_PROCESS=1",
    20  		"OTTO_PLUGIN_MIN_PORT=10000",
    21  		"OTTO_PLUGIN_MAX_PORT=25000",
    22  	}
    23  
    24  	cmd := exec.Command(os.Args[0], cs...)
    25  	cmd.Env = append(env, os.Environ()...)
    26  	return cmd
    27  }
    28  
    29  // This is not a real test. This is just a helper process kicked off by
    30  // tests.
    31  func TestHelperProcess(*testing.T) {
    32  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
    33  		return
    34  	}
    35  
    36  	defer os.Exit(0)
    37  
    38  	args := os.Args
    39  	for len(args) > 0 {
    40  		if args[0] == "--" {
    41  			args = args[1:]
    42  			break
    43  		}
    44  
    45  		args = args[1:]
    46  	}
    47  
    48  	if len(args) == 0 {
    49  		fmt.Fprintf(os.Stderr, "No command\n")
    50  		os.Exit(2)
    51  	}
    52  
    53  	cmd, args := args[0], args[1:]
    54  	switch cmd {
    55  	case "bad-version":
    56  		fmt.Printf("%s1|tcp|:1234\n", APIVersion)
    57  		<-make(chan int)
    58  	case "app":
    59  		Serve(&ServeOpts{
    60  			AppFunc: testAppFixed(new(app.Mock)),
    61  		})
    62  	case "invalid-rpc-address":
    63  		fmt.Println("lolinvalid")
    64  	case "mock":
    65  		fmt.Printf("%s|tcp|:1234\n", APIVersion)
    66  		<-make(chan int)
    67  	case "start-timeout":
    68  		time.Sleep(1 * time.Minute)
    69  		os.Exit(1)
    70  	case "stderr":
    71  		fmt.Printf("%s|tcp|:1234\n", APIVersion)
    72  		log.Println("HELLO")
    73  		log.Println("WORLD")
    74  	case "stdin":
    75  		fmt.Printf("%s|tcp|:1234\n", APIVersion)
    76  		data := make([]byte, 5)
    77  		if _, err := os.Stdin.Read(data); err != nil {
    78  			log.Printf("stdin read error: %s", err)
    79  			os.Exit(100)
    80  		}
    81  
    82  		if string(data) == "hello" {
    83  			os.Exit(0)
    84  		}
    85  
    86  		os.Exit(1)
    87  	default:
    88  		fmt.Fprintf(os.Stderr, "Unknown command: %q\n", cmd)
    89  		os.Exit(2)
    90  	}
    91  }
    92  
    93  func testAppFixed(p app.App) pluginrpc.AppFunc {
    94  	return func() app.App {
    95  		return p
    96  	}
    97  }