| 130 | } |
| 131 | |
| 132 | func TestJSONPbMarshalFields(t *testing.T) { |
| 133 | var m runtime.JSONPb |
| 134 | m.UseEnumNumbers = true // builtin fixtures include an enum, expected to be marshaled as int |
| 135 | |
| 136 | for _, spec := range builtinFieldFixtures { |
| 137 | m.Indent = spec.indent |
| 138 | |
| 139 | buf, err := m.Marshal(spec.data) |
| 140 | if err != nil { |
| 141 | t.Errorf("m.Marshal(%#v) failed with %v; want success", spec.data, err) |
| 142 | } |
| 143 | |
| 144 | if got, want := string(buf), spec.json; got != want { |
| 145 | t.Errorf("m.Marshal(%#v) = %q; want %q", spec.data, got, want) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // Reset m.Indent to ensure no unintended indentation settings carry over to subsequent tests |
| 150 | m.Indent = "" |
| 151 | |
| 152 | nums := []examplepb.NumericEnum{examplepb.NumericEnum_ZERO, examplepb.NumericEnum_ONE} |
| 153 | |
| 154 | buf, err := m.Marshal(nums) |
| 155 | if err != nil { |
| 156 | t.Errorf("m.Marshal(%#v) failed with %v; want success", nums, err) |
| 157 | } |
| 158 | if got, want := string(buf), `[0,1]`; got != want { |
| 159 | t.Errorf("m.Marshal(%#v) = %q; want %q", nums, got, want) |
| 160 | } |
| 161 | |
| 162 | m.UseEnumNumbers = false |
| 163 | buf, err = m.Marshal(examplepb.NumericEnum_ONE) |
| 164 | if err != nil { |
| 165 | t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) |
| 166 | } |
| 167 | if got, want := string(buf), `"ONE"`; got != want { |
| 168 | t.Errorf("m.Marshal(%#v) = %q; want %q", examplepb.NumericEnum_ONE, got, want) |
| 169 | } |
| 170 | |
| 171 | buf, err = m.Marshal(nums) |
| 172 | if err != nil { |
| 173 | t.Errorf("m.Marshal(%#v) failed with %v; want success", nums, err) |
| 174 | } |
| 175 | if got, want := string(buf), `["ZERO","ONE"]`; got != want { |
| 176 | t.Errorf("m.Marshal(%#v) = %q; want %q", nums, got, want) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | func TestJSONPbUnmarshal(t *testing.T) { |
| 181 | var ( |