github.com/supr/packer@v0.3.10-0.20131015195147-7b09e24ac3c1/packer/plugin/plugin_test.go (about)

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