1package test 2 3import ( 4 "encoding/json" 5 "github.com/json-iterator/go" 6 "testing" 7 "unicode/utf8" 8) 9 10func init() { 11 marshalCases = append(marshalCases, 12 `>`, 13 `"数字山谷"`, 14 "he\u2029\u2028he", 15 ) 16 for i := 0; i < utf8.RuneSelf; i++ { 17 marshalCases = append(marshalCases, string([]byte{byte(i)})) 18 } 19} 20 21func Test_read_string(t *testing.T) { 22 badInputs := []string{ 23 ``, 24 `"`, 25 `"\"`, 26 `"\\\"`, 27 "\"\n\"", 28 `"\U0001f64f"`, 29 `"\uD83D\u00"`, 30 } 31 for i := 0; i < 32; i++ { 32 // control characters are invalid 33 badInputs = append(badInputs, string([]byte{'"', byte(i), '"'})) 34 } 35 36 for _, input := range badInputs { 37 testReadString(t, input, "", true, "json.Unmarshal", json.Unmarshal) 38 testReadString(t, input, "", true, "jsoniter.Unmarshal", jsoniter.Unmarshal) 39 testReadString(t, input, "", true, "jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal) 40 } 41 42 goodInputs := []struct { 43 input string 44 expectValue string 45 }{ 46 {`""`, ""}, 47 {`"a"`, "a"}, 48 {`null`, ""}, 49 {`"Iñtërnâtiônàlizætiøn,⛔"`, "Iñtërnâtiônàlizætiøn,⛔"}, 50 {`"\uD83D"`, string([]byte{239, 191, 189})}, 51 {`"\uD83D\\"`, string([]byte{239, 191, 189, '\\'})}, 52 {`"\uD83D\ub000"`, string([]byte{239, 191, 189, 235, 128, 128})}, 53 {`"\uD83D\ude04"`, ""}, 54 {`"\uDEADBEEF"`, string([]byte{239, 191, 189, 66, 69, 69, 70})}, 55 {`"hel\"lo"`, `hel"lo`}, 56 {`"hel\\\/lo"`, `hel\/lo`}, 57 {`"hel\\blo"`, `hel\blo`}, 58 {`"hel\\\blo"`, "hel\\\blo"}, 59 {`"hel\\nlo"`, `hel\nlo`}, 60 {`"hel\\\nlo"`, "hel\\\nlo"}, 61 {`"hel\\tlo"`, `hel\tlo`}, 62 {`"hel\\flo"`, `hel\flo`}, 63 {`"hel\\\flo"`, "hel\\\flo"}, 64 {`"hel\\\rlo"`, "hel\\\rlo"}, 65 {`"hel\\\tlo"`, "hel\\\tlo"}, 66 {`"\u4e2d\u6587"`, "中文"}, 67 {`"\ud83d\udc4a"`, "\xf0\x9f\x91\x8a"}, 68 } 69 70 for _, tc := range goodInputs { 71 testReadString(t, tc.input, tc.expectValue, false, "json.Unmarshal", json.Unmarshal) 72 testReadString(t, tc.input, tc.expectValue, false, "jsoniter.Unmarshal", jsoniter.Unmarshal) 73 testReadString(t, tc.input, tc.expectValue, false, "jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal) 74 } 75} 76 77func testReadString(t *testing.T, input string, expectValue string, expectError bool, marshalerName string, marshaler func([]byte, interface{}) error) { 78 var value string 79 err := marshaler([]byte(input), &value) 80 if expectError != (err != nil) { 81 t.Errorf("%q: %s: expected error %v, got %v", input, marshalerName, expectError, err) 82 return 83 } 84 if value != expectValue { 85 t.Errorf("%q: %s: expected %q, got %q", input, marshalerName, expectValue, value) 86 return 87 } 88} 89