|
| 1 | +package csyaml |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | + |
| 9 | + "github.com/crowdsecurity/go-cs-lib/cstest" // adjust this import to your package |
| 10 | +) |
| 11 | + |
| 12 | +func TestIsEmptyYAML(t *testing.T) { |
| 13 | + tests := []struct { |
| 14 | + name string |
| 15 | + input string |
| 16 | + want bool |
| 17 | + wantErr string |
| 18 | + }{ |
| 19 | + { |
| 20 | + name: "empty document", |
| 21 | + input: ``, |
| 22 | + want: true, |
| 23 | + }, |
| 24 | + { |
| 25 | + name: "just a key", |
| 26 | + input: "foo:", |
| 27 | + want: false, |
| 28 | + }, |
| 29 | + { |
| 30 | + name: "just newline", |
| 31 | + input: "\n", |
| 32 | + want: true, |
| 33 | + }, |
| 34 | + { |
| 35 | + name: "just comment", |
| 36 | + input: "# only a comment", |
| 37 | + want: true, |
| 38 | + }, |
| 39 | + { |
| 40 | + name: "comments and empty lines", |
| 41 | + input: "# only a comment\n\n# another one\n\n", |
| 42 | + want: true, |
| 43 | + }, |
| 44 | + { |
| 45 | + name: "empty doc with separator", |
| 46 | + input: "---", |
| 47 | + want: true, |
| 48 | + }, |
| 49 | + { |
| 50 | + name: "empty mapping", |
| 51 | + input: "{}", |
| 52 | + want: false, |
| 53 | + }, |
| 54 | + { |
| 55 | + name: "empty sequence", |
| 56 | + input: "[]", |
| 57 | + want: false, |
| 58 | + }, |
| 59 | + { |
| 60 | + name: "non-empty mapping", |
| 61 | + input: "foo: bar", |
| 62 | + want: false, |
| 63 | + }, |
| 64 | + { |
| 65 | + name: "non-empty sequence", |
| 66 | + input: "- 1\n- 2", |
| 67 | + want: false, |
| 68 | + }, |
| 69 | + { |
| 70 | + name: "non-empty scalar", |
| 71 | + input: "hello", |
| 72 | + want: false, |
| 73 | + }, |
| 74 | + { |
| 75 | + name: "empty scalar", |
| 76 | + input: "''", |
| 77 | + want: false, |
| 78 | + }, |
| 79 | + { |
| 80 | + name: "explicit nil", |
| 81 | + input: "null", |
| 82 | + want: false, |
| 83 | + }, |
| 84 | + { |
| 85 | + name: "malformed YAML", |
| 86 | + input: "foo: [1,", |
| 87 | + wantErr: "[1:6] sequence end token ']' not found", |
| 88 | + }, |
| 89 | + { |
| 90 | + name: "multiple empty documents", |
| 91 | + input: "---\n---\n---\n#comment", |
| 92 | + want: true, |
| 93 | + }, |
| 94 | + { |
| 95 | + name: "second document is not empty", |
| 96 | + input: "---\nfoo: bar\n---\n#comment", |
| 97 | + want: false, |
| 98 | + }, |
| 99 | + } |
| 100 | + |
| 101 | + for _, tc := range tests { |
| 102 | + t.Run(tc.name, func(t *testing.T) { |
| 103 | + got, err := IsEmptyYAML(strings.NewReader(tc.input)) |
| 104 | + |
| 105 | + cstest.RequireErrorContains(t, err, tc.wantErr) |
| 106 | + |
| 107 | + if tc.wantErr != "" { |
| 108 | + return |
| 109 | + } |
| 110 | + |
| 111 | + assert.Equal(t, tc.want, got) |
| 112 | + }) |
| 113 | + } |
| 114 | +} |
0 commit comments