github.com/UlisseMini/utils@v0.0.0-20181216031219-f016c7ea9463/test/test.go (about)

     1  // package test implements an easy way to test the output of programs.
     2  package test
     3  
     4  import (
     5  	"context"
     6  	"errors"
     7  	"fmt"
     8  	"os/exec"
     9  	"time"
    10  )
    11  
    12  // a Case is used for testing the output of a program
    13  type Case struct {
    14  	// Path is the path to the executeable
    15  	Path string
    16  
    17  	// Expected is the expected output from the executeable
    18  	Expected string
    19  
    20  	// Time to wait for the program to finish
    21  	Timeout time.Duration
    22  }
    23  
    24  func (t Case) Run() error {
    25  	// context for timing out the command (if they supplied timeout field)
    26  	ctx := context.Background()
    27  	if t.Timeout != 0 {
    28  		ctx, _ = context.WithTimeout(ctx, t.Timeout)
    29  	}
    30  
    31  	// create the command
    32  	cmd := exec.CommandContext(ctx, t.Path)
    33  
    34  	stdout, err := cmd.Output()
    35  	if err != nil {
    36  		// i wish there was a better way to do this :l
    37  		if err.Error() == "signal: killed" {
    38  			return errors.New("timeout exceeded")
    39  		}
    40  
    41  		return err
    42  	}
    43  
    44  	// check standard out
    45  	if string(stdout) != t.Expected {
    46  		return fmt.Errorf("Expected %q got %q", t.Expected, stdout)
    47  	}
    48  
    49  	return nil
    50  }