github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/builder/dockerfile/parser/json_test.go (about)

     1  package parser
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  var invalidJSONArraysOfStrings = []string{
     8  	`["a",42,"b"]`,
     9  	`["a",123.456,"b"]`,
    10  	`["a",{},"b"]`,
    11  	`["a",{"c": "d"},"b"]`,
    12  	`["a",["c"],"b"]`,
    13  	`["a",true,"b"]`,
    14  	`["a",false,"b"]`,
    15  	`["a",null,"b"]`,
    16  }
    17  
    18  var validJSONArraysOfStrings = map[string][]string{
    19  	`[]`:           {},
    20  	`[""]`:         {""},
    21  	`["a"]`:        {"a"},
    22  	`["a","b"]`:    {"a", "b"},
    23  	`[ "a", "b" ]`: {"a", "b"},
    24  	`[	"a",	"b"	]`: {"a", "b"},
    25  	`	[	"a",	"b"	]	`: {"a", "b"},
    26  	`["abc 123", "♥", "☃", "\" \\ \/ \b \f \n \r \t \u0000"]`: {"abc 123", "♥", "☃", "\" \\ / \b \f \n \r \t \u0000"},
    27  }
    28  
    29  func TestJSONArraysOfStrings(t *testing.T) {
    30  	for json, expected := range validJSONArraysOfStrings {
    31  		d := Directive{}
    32  		SetEscapeToken(DefaultEscapeToken, &d)
    33  
    34  		if node, _, err := parseJSON(json, &d); err != nil {
    35  			t.Fatalf("%q should be a valid JSON array of strings, but wasn't! (err: %q)", json, err)
    36  		} else {
    37  			i := 0
    38  			for node != nil {
    39  				if i >= len(expected) {
    40  					t.Fatalf("expected result is shorter than parsed result (%d vs %d+) in %q", len(expected), i+1, json)
    41  				}
    42  				if node.Value != expected[i] {
    43  					t.Fatalf("expected %q (not %q) in %q at pos %d", expected[i], node.Value, json, i)
    44  				}
    45  				node = node.Next
    46  				i++
    47  			}
    48  			if i != len(expected) {
    49  				t.Fatalf("expected result is longer than parsed result (%d vs %d) in %q", len(expected), i+1, json)
    50  			}
    51  		}
    52  	}
    53  	for _, json := range invalidJSONArraysOfStrings {
    54  		d := Directive{}
    55  		SetEscapeToken(DefaultEscapeToken, &d)
    56  
    57  		if _, _, err := parseJSON(json, &d); err != errDockerfileNotStringArray {
    58  			t.Fatalf("%q should be an invalid JSON array of strings, but wasn't!", json)
    59  		}
    60  	}
    61  }