|
| 1 | +package terraform |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/hashicorp/hcl/v2" |
| 7 | + "github.com/hashicorp/hcl/v2/hclsyntax" |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | +) |
| 11 | + |
| 12 | +func Test_EscapeSpecialSequences(t *testing.T) { |
| 13 | + tests := []struct { |
| 14 | + name string |
| 15 | + inp string |
| 16 | + expected string |
| 17 | + }{ |
| 18 | + { |
| 19 | + name: "without special sequences", |
| 20 | + inp: `"hello world\\"`, |
| 21 | + expected: `"hello world\\"`, |
| 22 | + }, |
| 23 | + { |
| 24 | + name: "interpolation", |
| 25 | + inp: `"Hello, ${var.name}!"`, |
| 26 | + expected: `"Hello, $${var.name}!"`, |
| 27 | + }, |
| 28 | + { |
| 29 | + name: "directive", |
| 30 | + inp: `"Hello, %{ if true }foo%{ else }bar%{ endif }!"`, |
| 31 | + expected: `"Hello, %%{ if true }foo%%{ else }bar%%{ endif }!"`, |
| 32 | + }, |
| 33 | + { |
| 34 | + name: "interpolation already escaped", |
| 35 | + inp: `"Hello, $${var.name}!"`, |
| 36 | + expected: `"Hello, $${var.name}!"`, |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "start with special character", |
| 40 | + inp: `${var.name}!"`, |
| 41 | + expected: `$${var.name}!"`, |
| 42 | + }, |
| 43 | + { |
| 44 | + name: "grok pattern", |
| 45 | + inp: "# Grok Pattern Template\ngrok_pattern = \"%{TIMESTAMP_ISO8601:time} \\\\[%{NUMBER:pid}\\\\] %{GREEDYDATA:message}\"", |
| 46 | + expected: "# Grok Pattern Template\ngrok_pattern = \"%%{TIMESTAMP_ISO8601:time} \\\\[%%{NUMBER:pid}\\\\] %%{GREEDYDATA:message}\"", |
| 47 | + }, |
| 48 | + } |
| 49 | + |
| 50 | + for _, tt := range tests { |
| 51 | + t.Run(tt.name, func(t *testing.T) { |
| 52 | + got := escapeSpecialSequences(tt.inp) |
| 53 | + assert.Equal(t, tt.expected, got) |
| 54 | + |
| 55 | + // We make sure that the characters are properly escaped |
| 56 | + _, diag := hclsyntax.ParseTemplate([]byte(got), "", hcl.InitialPos) |
| 57 | + if diag.HasErrors() { |
| 58 | + require.NoError(t, diag) |
| 59 | + } |
| 60 | + }) |
| 61 | + } |
| 62 | +} |
0 commit comments