|
| 1 | +package jsonc |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +func ts(b []byte) *Decoder { return &Decoder{r: bytes.NewBuffer(b)} } |
| 9 | + |
| 10 | +var ( |
| 11 | + validSingle = []byte(`{"foo": // this is a single line comment\n"bar foo", "true": false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com" }`) |
| 12 | + invalidSingle = []byte(`{"foo": // this is a single line comment "bar foo", "true": false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com" }`) |
| 13 | + |
| 14 | + validBlock = []byte(`{"foo": /* this is a block comment */ "bar foo", "true": false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com" }`) |
| 15 | + invalidBlock = []byte(`{"foo": /* this is a block comment "bar foo", "true": false, "number": 42, "object": { "test": "done" }, "array" : [1, 2, 3], "url" : "https://github.com" }`) |
| 16 | +) |
| 17 | + |
| 18 | +func Test_Decoder_Read(t *testing.T) { |
| 19 | + |
| 20 | + type args struct { |
| 21 | + p []byte |
| 22 | + } |
| 23 | + |
| 24 | + tests := []struct { |
| 25 | + name string |
| 26 | + d *Decoder |
| 27 | + args args |
| 28 | + want int |
| 29 | + wantErr bool |
| 30 | + }{ |
| 31 | + { |
| 32 | + name: "Valid single line comment", |
| 33 | + d: ts(validSingle), |
| 34 | + args: args{p: make([]byte, len(validSingle))}, |
| 35 | + want: 110, // (163(total) - 34(comments) - 19(spaces)) |
| 36 | + wantErr: false, |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "Invalid single line comment", |
| 40 | + d: ts(invalidSingle), |
| 41 | + args: args{p: make([]byte, len(invalidSingle))}, |
| 42 | + want: 0, |
| 43 | + wantErr: true, |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "Valid block comment", |
| 47 | + d: ts(validBlock), |
| 48 | + args: args{p: make([]byte, len(validBlock))}, |
| 49 | + want: 110, // (159(total) - 29(comments) - 20(spaces)) |
| 50 | + wantErr: false, |
| 51 | + }, |
| 52 | + { |
| 53 | + name: "Invalid block comment", |
| 54 | + d: ts(invalidBlock), |
| 55 | + args: args{p: make([]byte, len(invalidBlock))}, |
| 56 | + want: 0, |
| 57 | + wantErr: true, |
| 58 | + }, |
| 59 | + } |
| 60 | + |
| 61 | + for _, tt := range tests { |
| 62 | + t.Run(tt.name, func(t *testing.T) { |
| 63 | + got, err := tt.d.Read(tt.args.p) |
| 64 | + if (err != nil) != tt.wantErr { |
| 65 | + t.Errorf("Decoder.Read() error = %v, wantErr %v", err, tt.wantErr) |
| 66 | + return |
| 67 | + } |
| 68 | + if got != tt.want { |
| 69 | + t.Errorf("Decoder.Read() = %v, want %v", got, tt.want) |
| 70 | + } |
| 71 | + }) |
| 72 | + } |
| 73 | +} |
0 commit comments