github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/packer/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  
    12  func helperProcess(s ...string) *exec.Cmd {
    13  	cs := []string{"-test.run=TestHelperProcess", "--"}
    14  	cs = append(cs, s...)
    15  	env := []string{
    16  		"GO_WANT_HELPER_PROCESS=1",
    17  		"PACKER_PLUGIN_MIN_PORT=10000",
    18  		"PACKER_PLUGIN_MAX_PORT=25000",
    19  	}
    20  
    21  	cmd := exec.Command(os.Args[0], cs...)
    22  	cmd.Env = append(env, os.Environ()...)
    23  	return cmd
    24  }
    25  
    26  // This is not a real test. This is just a helper process kicked off by
    27  // tests.
    28  func TestHelperProcess(*testing.T) {
    29  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
    30  		return
    31  	}
    32  
    33  	defer os.Exit(0)
    34  
    35  	args := os.Args
    36  	for len(args) > 0 {
    37  		if args[0] == "--" {
    38  			args = args[1:]
    39  			break
    40  		}
    41  
    42  		args = args[1:]
    43  	}
    44  
    45  	if len(args) == 0 {
    46  		fmt.Fprintf(os.Stderr, "No command\n")
    47  		os.Exit(2)
    48  	}
    49  
    50  	cmd, args := args[0], args[1:]
    51  	switch cmd {
    52  	case "builder":
    53  		ServeBuilder(new(helperBuilder))
    54  	case "command":
    55  		ServeCommand(new(helperCommand))
    56  	case "hook":
    57  		ServeHook(new(helperHook))
    58  	case "invalid-rpc-address":
    59  		fmt.Println("lolinvalid")
    60  	case "mock":
    61  		fmt.Println(":1234")
    62  		<-make(chan int)
    63  	case "post-processor":
    64  		ServePostProcessor(new(helperPostProcessor))
    65  	case "provisioner":
    66  		ServeProvisioner(new(helperProvisioner))
    67  	case "start-timeout":
    68  		time.Sleep(1 * time.Minute)
    69  		os.Exit(1)
    70  	case "stderr":
    71  		fmt.Println(":1234")
    72  		log.Println("HELLO")
    73  		log.Println("WORLD")
    74  	case "stdin":
    75  		fmt.Println(":1234")
    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  }