import 'dart:convert'; import 'package:ch12_json/src/decoding.dart'; import 'package:ch12_json/src/json_basics.dart'; import 'package:ch12_json/src/models_generated.dart'; import 'package:ch12_json/src/models_manual.dart'; import 'package:ch12_json/src/order_parser.dart'; import 'package:ch12_json/src/perf.dart'; import 'package:test/test.dart'; void main() { group('dart:convert 基础', () { test('JSON 值映射成 Dart 类型', () { final Object? value = decodeJson('{"s":"x","i":1,"d":1.5,"b":true,"n":null,"l":[1]}'); expect(value, isA>()); final Map map = value! as Map; expect(map['s'], isA()); expect(map['i'], isA()); expect(map['d'], isA()); expect(map['b'], isA()); expect(map['n'], isNull); expect(map['l'], isA>()); }); test('数字形状:整数字面量 → int,小数/指数 → double', () { final ({Object? asDouble, Object? asExponent, Object? asInt}) shapes = numberShapes(); expect(shapes.asInt, 1); expect(shapes.asInt, isA()); expect(shapes.asDouble, 1.0); expect(shapes.asDouble, isA()); expect(shapes.asExponent, 1000.0); expect(shapes.asExponent, isA()); }); test('编码不可 JSON 化的类型会抛 JsonUnsupportedObjectError', () { expect(canEncode({'ok': 1}), isTrue); expect(canEncode({'t': DateTime(2024)}), isFalse); expect(canEncode({'s': {1, 2}}), isFalse); expect(() => encodeJson(DateTime(2024)), throwsA(isA())); }); test('美化编码与紧凑编码语义一致', () { const Map value = {'a': [1, 2], 'b': {'c': 'd'}}; expect(encodePretty(value), contains('\n')); expect(decodeJson(encodePretty(value)), decodeJson(encodeJson(value))); }); test('UTF-8 与转义:中文原样保留,控制字符被转义', () { expect(encodeJson({'k': '中文'}), '{"k":"中文"}'); expect(encodeJson('a\nb'), '"a\\nb"'); expect(decodeJson('"\\u4e2d"'), '中'); }); }); group('手写模型', () { const String json = ''' { "id": "u-1", "email": "ada@example.com", "name": "Ada", "tier": "pro", "tags": ["math", 42, "computing"], "address": {"city": "London", "zip": "W1"}, "created_at": "1815-12-10T00:00:00Z", "unknown": "ignored" } '''; test('fromJson 处理嵌套、可空、枚举、过滤错误类型的列表元素', () { final User user = User.fromJson(jsonDecode(json) as Map); expect(user.id, 'u-1'); expect(user.name, 'Ada'); expect(user.tier, Tier.pro); expect(user.tags, ['math', 'computing']); // 42 被过滤 expect(user.address?.city, 'London'); expect(user.address?.street, isNull); expect(user.createdAt, DateTime.utc(1815, 12, 10)); }); test('toJson / fromJson 往返', () { final User user = User.fromJson(jsonDecode(json) as Map); final User again = User.fromJson(decodeJson(encodeJson(user.toJson()))! as Map); expect(again.id, user.id); expect(again.tags, user.tags); expect(again.tier, user.tier); expect(again.address, user.address); // Address 重写了 == expect(again.createdAt, user.createdAt); }); test('缺省字段与未知枚举值', () { final User user = User.fromJson({'id': 'x', 'email': 'x@y'}); expect(user.tier, Tier.free); // 缺 tier → free expect(user.tags, isEmpty); expect(user.address, isNull); expect(user.createdAt, isNull); expect(user.displayName, 'x'); // name 缺失 → 用邮箱前缀 final User unknownTier = User.fromJson({ 'id': 'x', 'email': 'x@y', 'tier': 'platinum', }); expect(unknownTier.tier, Tier.free); // 未知值降级 }); test('必需字段缺失时抛 TypeError', () { expect(() => User.fromJson({'email': 'a@b'}), throwsA(isA())); }); test('订单:列表嵌套与计算值', () { final Order order = Order.fromJson({ 'id': 'o-1', 'items': [ {'sku': 'a', 'quantity': 2, 'unit_cents': 150}, 'not-an-object', {'sku': 'b', 'quantity': 1, 'unit_cents': 500}, ], }); expect(order.items, hasLength(2)); // 非法元素被跳过 expect(order.totalCents, 800); expect(Order.fromJson(order.toJson()).totalCents, 800); }); }); group('json_serializable 生成模型', () { const String json = ''' { "id": "a-1", "email": "grace@example.com", "display_name": "Grace", "balance_cents": 1200, "tags": ["navy"], "address": {"city": "NYC", "zip": "10001"}, "tier": "pro", "created_at": "2024-05-01T08:30:00Z", "is_active": false } '''; test('snake_case 映射、显式重命名、默认值', () { final Account a = Account.fromJson(jsonDecode(json) as Map); expect(a.displayName, 'Grace'); expect(a.balanceCents, 1200); expect(a.tier, Tier.pro); expect(a.createdAt, DateTime.utc(2024, 5, 1, 8, 30)); expect(a.isActive, isFalse); expect(a.address?.city, 'NYC'); expect(a.tags, ['navy']); }); test('缺字段时走 defaultValue', () { final Account a = Account.fromJson({'id': 'x', 'email': 'x@y'}); expect(a.balanceCents, 0); expect(a.isActive, isTrue); expect(a.tier, Tier.free); expect(a.tags, isEmpty); expect(a.address, isNull); }); test('未知枚举值降级为 free 而不是抛异常', () { final Account a = Account.fromJson({ 'id': 'x', 'email': 'x@y', 'tier': 'enterprise', }); expect(a.tier, Tier.free); }); test('toJson 里的嵌套 Address 已被序列化(可 jsonEncode)', () { final Account a = Account.fromJson(jsonDecode(json) as Map); final Map out = a.toJson(); expect(out['address'], isA>()); expect(() => encodeJson(out), returnsNormally); expect(decodeJson(encodeJson(out))! as Map, containsPair('display_name', 'Grace')); }); test('includeFromJson/includeToJson: false 的字段不参与序列化', () { final Account a = Account.fromJson({ 'id': 'x', 'email': 'x@y', 'local_only': '不应被读入', }); expect(a.localOnly, ''); // 输入里的 local_only 被忽略 final Account withLocal = Account(id: 'x', email: 'x@y', localOnly: '仅本机'); final Map out = withLocal.toJson(); expect(out.containsKey('localOnly'), isFalse); expect(out.containsKey('local_only'), isFalse); expect(encodeJson(out), isNot(contains('仅本机'))); }); test('explicitToJson:Payload 递归序列化', () { final Account a = Account.fromJson({'id': 'x', 'email': 'x@y'}); final Payload p = Payload(account: a, extra: {'trace': 't-1'}); final Map out = p.toJson(); expect(out['account'], isA>()); expect(out['extra'], {'trace': 't-1'}); expect(() => encodeJson(out), returnsNormally); }); }); group('健壮解码', () { test('语法错误:FormatException 被包装成 JsonParseException', () { expect( () => decodeModel('{"id": "u-1",}', User.fromJson), throwsA(isA().having((JsonParseException e) => e.message, 'message', contains('语法'))), ); }); test('顶层类型错误', () { expect(() => decodeModel('[]', User.fromJson), throwsA(isA())); }); test('字段类型错误被识别', () { expect( () => decodeModel('{"id": 1, "email": "a@b"}', User.fromJson), throwsA(isA()), ); }); test('路径感知的解析:错误精确到字段与下标', () { expect( () => parseOrderStrict({ 'id': 'o-1', 'items': [ {'sku': 'a', 'quantity': 1, 'unit_cents': 100}, {'sku': 'b', 'quantity': 1.5, 'unit_cents': 200}, ], }), throwsA(isA() .having((JsonParseException e) => e.path, 'path', r'$.items[1].quantity')), ); expect( () => parseOrderStrict({'id': 'o-1', 'items': 'not-a-list'}), throwsA(isA().having((JsonParseException e) => e.path, 'path', r'$.items')), ); }); test('expectInt 接受整数值的 double,拒绝 1.5', () { expect(expectInt(3, r'$.x'), 3); expect(expectInt(3.0, r'$.x'), 3); expect(() => expectInt(3.5, r'$.x'), throwsA(isA())); expect(() => expectInt('3', r'$.x'), throwsA(isA())); }); test('decodeList 解析数组并标注下标', () { final List users = decodeList( '[{"id":"a","email":"a@x"},{"id":"b","email":"b@x"}]', User.fromJson, ); expect(users.map((User u) => u.id), ['a', 'b']); expect( () => decodeList('[{"id":"a","email":"a@x"}, 42]', User.fromJson), throwsA(isA().having((JsonParseException e) => e.path, 'path', r'$[1]')), ); }); }); group('大 JSON 与 isolate', () { test('生成、解码、重新编码都不丢行数', () async { final String raw = buildFixture(2000); expect(countRows(raw), 2000); expect(reEncode(raw), isNotEmpty); expect(await countRowsInIsolate(raw), 2000); }); test('格式不对时抛 FormatException', () { expect(() => countRows('{"rows": 1}'), throwsA(isA())); expect(() => countRows('[]'), throwsA(isA())); }); }); }