github.com/tompao/docker@v1.9.1/builder/dockerfile/shell_parser_test.go (about)

     1  package dockerfile
     2  
     3  import (
     4  	"bufio"
     5  	"os"
     6  	"strings"
     7  	"testing"
     8  )
     9  
    10  func TestShellParser(t *testing.T) {
    11  	file, err := os.Open("words")
    12  	if err != nil {
    13  		t.Fatalf("Can't open 'words': %s", err)
    14  	}
    15  	defer file.Close()
    16  
    17  	scanner := bufio.NewScanner(file)
    18  	envs := []string{"PWD=/home", "SHELL=bash"}
    19  	for scanner.Scan() {
    20  		line := scanner.Text()
    21  
    22  		// Trim comments and blank lines
    23  		i := strings.Index(line, "#")
    24  		if i >= 0 {
    25  			line = line[:i]
    26  		}
    27  		line = strings.TrimSpace(line)
    28  
    29  		if line == "" {
    30  			continue
    31  		}
    32  
    33  		words := strings.Split(line, "|")
    34  		if len(words) != 2 {
    35  			t.Fatalf("Error in 'words' - should be 2 words:%q", words)
    36  		}
    37  
    38  		words[0] = strings.TrimSpace(words[0])
    39  		words[1] = strings.TrimSpace(words[1])
    40  
    41  		newWord, err := ProcessWord(words[0], envs)
    42  
    43  		if err != nil {
    44  			newWord = "error"
    45  		}
    46  
    47  		if newWord != words[1] {
    48  			t.Fatalf("Error. Src: %s  Calc: %s  Expected: %s", words[0], newWord, words[1])
    49  		}
    50  	}
    51  }
    52  
    53  func TestGetEnv(t *testing.T) {
    54  	sw := &shellWord{
    55  		word: "",
    56  		envs: nil,
    57  		pos:  0,
    58  	}
    59  
    60  	sw.envs = []string{}
    61  	if sw.getEnv("foo") != "" {
    62  		t.Fatalf("2 - 'foo' should map to ''")
    63  	}
    64  
    65  	sw.envs = []string{"foo"}
    66  	if sw.getEnv("foo") != "" {
    67  		t.Fatalf("3 - 'foo' should map to ''")
    68  	}
    69  
    70  	sw.envs = []string{"foo="}
    71  	if sw.getEnv("foo") != "" {
    72  		t.Fatalf("4 - 'foo' should map to ''")
    73  	}
    74  
    75  	sw.envs = []string{"foo=bar"}
    76  	if sw.getEnv("foo") != "bar" {
    77  		t.Fatalf("5 - 'foo' should map to 'bar'")
    78  	}
    79  
    80  	sw.envs = []string{"foo=bar", "car=hat"}
    81  	if sw.getEnv("foo") != "bar" {
    82  		t.Fatalf("6 - 'foo' should map to 'bar'")
    83  	}
    84  	if sw.getEnv("car") != "hat" {
    85  		t.Fatalf("7 - 'car' should map to 'hat'")
    86  	}
    87  
    88  	// Make sure we grab the first 'car' in the list
    89  	sw.envs = []string{"foo=bar", "car=hat", "car=bike"}
    90  	if sw.getEnv("car") != "hat" {
    91  		t.Fatalf("8 - 'car' should map to 'hat'")
    92  	}
    93  }