vitess.io/vitess@v0.16.2/go/jsonutil/json_test.go (about) 1 /* 2 Copyright 2020 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package jsonutil 18 19 import ( 20 "testing" 21 ) 22 23 func TestMarshalNoEscape(t *testing.T) { 24 cases := []struct { 25 name string 26 v any 27 expected string 28 }{ 29 { 30 name: "normal", 31 v: struct { 32 Usr string 33 Pwd string 34 }{ 35 Usr: "vitess", 36 Pwd: "vitess", 37 }, 38 expected: "{\"Usr\":\"vitess\",\"Pwd\":\"vitess\"}", 39 }, 40 { 41 name: "not exported", 42 v: struct { 43 usr string 44 pwd string 45 }{ 46 usr: "vitess", 47 pwd: "vitess", 48 }, 49 expected: "{}", 50 }, 51 } 52 for _, c := range cases { 53 t.Run(c.name, func(t *testing.T) { 54 json, _ := MarshalNoEscape(c.v) 55 sjson := string(json[:len(json)-1]) 56 if sjson != c.expected { 57 t.Errorf("expected: %v, got: %v", c.expected, sjson) 58 } 59 }) 60 } 61 } 62 63 func TestMarshalIndentNoEscape(t *testing.T) { 64 cases := []struct { 65 name string 66 v any 67 prefix string 68 ident string 69 expected string 70 }{ 71 { 72 name: "normal", 73 v: struct { 74 Usr string 75 Pwd string 76 }{ 77 Usr: "vitess", 78 Pwd: "vitess", 79 }, 80 prefix: "test", 81 ident: "\t", 82 expected: "{\ntest\t\"Usr\": \"vitess\",\ntest\t\"Pwd\": \"vitess\"\ntest}", 83 }, 84 { 85 name: "not exported", 86 v: struct { 87 usr string 88 pwd string 89 }{ 90 usr: "vitess", 91 pwd: "vitess", 92 }, 93 expected: "{}", 94 }, 95 } 96 for _, c := range cases { 97 t.Run(c.name, func(t *testing.T) { 98 json, _ := MarshalIndentNoEscape(c.v, c.prefix, c.ident) 99 sjson := string(json[:len(json)-1]) 100 if sjson != c.expected { 101 t.Errorf("expected: %v, got: %v", c.expected, sjson) 102 } 103 }) 104 } 105 }