验证标准 json.Marshal 确实是不确定的
(t *testing.T)
| 282 | |
| 283 | // 验证标准 json.Marshal 确实是不确定的 |
| 284 | func TestStandardJSONIsNonDeterministic(t *testing.T) { |
| 285 | m := map[string]int{ |
| 286 | "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, |
| 287 | "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, |
| 288 | } |
| 289 | |
| 290 | // 多次序列化,看是否产生不同结果 |
| 291 | seen := make(map[string]bool) |
| 292 | for range 100 { |
| 293 | data, _ := json.Marshal(m) |
| 294 | seen[string(data)] = true |
| 295 | } |
| 296 | |
| 297 | // 注意:这个测试可能偶尔失败,因为运气好的话所有输出可能相同 |
| 298 | // 但对于有足够多 key 的 map,大概率会产生不同输出 |
| 299 | if len(seen) == 1 { |
| 300 | t.Log("Warning: Standard json.Marshal produced consistent output in all iterations") |
| 301 | t.Log("This is expected behavior for Go 1.12+, but map iteration order is still not guaranteed") |
| 302 | } |
| 303 | } |