shell_parser_test.go 1.8 KB

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