Replace json_utils with a modern extension type, add tests. (flutter/engine#52769)

I started on a refactoring of
https://github.com/flutter/flutter/issues/147666, and was frustrated
with the JSON decoding of `gn desc --format=json`, so I used a similar
pattern from my micro-json library (https://pub.dev/packages/jsonut) and
encapsulated it as an extension type.

My favorite is the `JsonObject.map` function which replaces:

```dart
/// Construct a RunTarget from a JSON map.
factory RunTarget.fromJson(Map<String, Object> map) {
  final List<String> errors = <String>[];
  final String name = stringOfJson(map, _nameKey, errors)!;
  final String id = stringOfJson(map, _idKey, errors)!;
  final String targetPlatform =
      stringOfJson(map, _targetPlatformKey, errors)!;

  if (errors.isNotEmpty) {
    throw FormatException('Failed to parse RunTarget: ${errors.join('\n')}');
  }
  return RunTarget._(name, id, targetPlatform);
}
```

... with:

```dart
/// Construct a RunTarget from a JSON map.
factory RunTarget.fromJson(Map<String, Object> map) {
  return JsonObject(map).map((JsonObject json) => RunTarget._(
    json.string(_nameKey),
    json.string(_idKey),
    json.string(_targetPlatformKey),
  ));
}
```
This commit is contained in:
Matan Lurey
2024-05-13 20:03:43 -07:00
committed by GitHub
parent 3c17cf0357
commit d89f54dd65
7 changed files with 663 additions and 160 deletions

View File

@@ -11,8 +11,8 @@ import 'package:process_runner/process_runner.dart';
import 'build_utils.dart';
import 'environment.dart';
import 'json_utils.dart';
import 'proc_utils.dart';
import 'typed_json.dart';
/// Canonicalized build targets start with this prefix.
const String buildTargetPrefix = '//';
@@ -86,9 +86,8 @@ Future<Map<String, BuildTarget>> findTargets(
environment.logger
.fatal('gn desc output is malformed $label has no value.');
}
final Map<String, Object?> properties =
targetEntry.value! as Map<String, Object?>;
final String? typeString = getString(properties, 'type');
final JsonObject properties = JsonObject(targetEntry.value! as Map<String, Object?>);
final String? typeString = properties.stringOrNull('type');
if (typeString == null) {
environment.logger.fatal('gn desc is missing target type: $properties');
}
@@ -97,7 +96,7 @@ Future<Map<String, BuildTarget>> findTargets(
// Target is a type that we don't support.
continue;
}
final bool testOnly = getBool(properties, 'testonly');
final bool testOnly = properties.boolean('testonly');
final List<String> outputs =
await _runGnOutputs(buildDir.path, label, environment);
File? executable;

View File

@@ -1,119 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
void _appendTypeError(
Map<String, Object?> map,
String field,
String expected,
List<String> errors, {
Object? element,
}) {
if (element == null) {
final Type actual = map[field]!.runtimeType;
errors.add(
'For field "$field", expected type: $expected, actual type: $actual.',
);
} else {
final Type actual = element.runtimeType;
errors.add(
'For element "$element" of "$field", '
'expected type: $expected, actual type: $actual',
);
}
}
/// Type safe getter of a List<String> field from map.
List<String>? stringListOfJson(
Map<String, Object?> map,
String field,
List<String> errors,
) {
if (map[field] == null) {
return <String>[];
}
if (map[field]! is! List<Object?>) {
_appendTypeError(map, field, 'list', errors);
return null;
}
for (final Object? obj in map[field]! as List<Object?>) {
if (obj is! String) {
_appendTypeError(map, field, element: obj, 'string', errors);
return null;
}
}
return (map[field]! as List<Object?>).cast<String>();
}
/// Type safe getter of a String field from map.
String? stringOfJson(
Map<String, Object?> map,
String field,
List<String> errors,
) {
if (map[field] == null) {
return '<undef>';
}
if (map[field]! is! String) {
_appendTypeError(map, field, 'string', errors);
return null;
}
return map[field]! as String;
}
/// Type safe getter of an int field from map.
int? intOfJson(
Map<String, Object?> map,
String field,
List<String> errors, {
int fallback = 0,
}) {
if (map[field] == null) {
return fallback;
}
if (map[field]! is! int) {
_appendTypeError(map, field, 'int', errors);
return null;
}
return map[field]! as int;
}
const JsonEncoder _jsonEncoder = JsonEncoder.withIndent(' ');
/// Same as [jsonEncode] but is formatted to be human readable.
String jsonEncodePretty(Object? object) => _jsonEncoder.convert(object);
/// Returns the value in map[field] iff it is a String. null otherwise.
String? getString(Map<String, Object?> map, String field) {
if (map[field] case final String value) {
return value;
}
return null;
}
/// Returns the value in map[field] iff it is a bool. missingValue otherwise.
bool getBool(Map<String, Object?> map, String field,
[bool missingValue = false]) {
if (map[field] case final bool value) {
return value;
}
return missingValue;
}
/// Returns the value in map[field] iff it is a List<String>. null otherwise.
List<String>? getListOfString(Map<String, Object?> map, String field) {
if (map[field] == null) {
return null;
}
if (map[field]! is! List<Object?>) {
return null;
}
for (final Object? obj in map[field]! as List<Object?>) {
if (obj is! String) {
return null;
}
}
return (map[field]! as List<Object?>).cast<String>();
}

View File

@@ -3,7 +3,6 @@
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
@@ -11,8 +10,8 @@ import 'package:path/path.dart' as p;
import 'package:process_runner/process_runner.dart';
import 'environment.dart';
import 'json_utils.dart';
import 'logger.dart';
import 'typed_json.dart';
import 'worker_pool.dart';
/// Artifacts from an exited sub-process.
@@ -33,18 +32,18 @@ final class ProcessArtifacts {
/// Constructs an instance of ProcessArtifacts from serialized JSON text.
factory ProcessArtifacts.fromJson(String serialized) {
final Map<String, dynamic> artifact =
jsonDecode(serialized) as Map<String, dynamic>;
final List<String> errors = <String>[];
final Directory cwd = Directory(stringOfJson(artifact, 'cwd', errors)!);
final List<String> commandLine =
stringListOfJson(artifact, 'commandLine', errors)!;
final int exitCode = intOfJson(artifact, 'exitCode', errors)!;
final String stdout = stringOfJson(artifact, 'stdout', errors)!;
final String stderr = stringOfJson(artifact, 'stderr', errors)!;
final int? pid = intOfJson(artifact, 'pid', errors);
return ProcessArtifacts(cwd, commandLine, exitCode, stdout, stderr,
pid: pid);
final JsonObject artifact = JsonObject.parse(serialized);
return artifact.map((JsonObject json) => ProcessArtifacts(
Directory(json.string('cwd')),
json.stringList('commandLine'),
json.integer('exitCode'),
json.string('stdout'),
json.string('stderr'),
pid: json.integer('pid'),
), onError: (JsonObject source, JsonMapException e) {
throw FormatException('Failed to parse ProcessArtifacts: $e', source.toPrettyString());
},
);
}
/// Constructs an instance of ProcessArtifacts from a file containing JSON.
@@ -54,16 +53,14 @@ final class ProcessArtifacts {
/// Saves ProcessArtifacts into file.
void save(File file) {
final Map<String, Object> data = <String, Object>{};
if (pid != null) {
data['pid'] = pid!;
}
data['exitCode'] = exitCode;
data['stdout'] = stdout;
data['stderr'] = stderr;
data['cwd'] = cwd.absolute.path;
data['commandLine'] = commandLine;
file.writeAsStringSync(jsonEncodePretty(data));
file.writeAsStringSync(JsonObject(<String, Object?>{
if (pid != null) 'pid': pid,
'exitCode': exitCode,
'stdout': stdout,
'stderr': stderr,
'cwd': cwd.absolute.path,
'commandLine': commandLine,
}).toPrettyString());
}
/// Creates a temporary file and saves the artifacts into it.

View File

@@ -7,7 +7,7 @@ import 'dart:convert';
import 'package:process_runner/process_runner.dart';
import 'environment.dart';
import 'json_utils.dart';
import 'typed_json.dart';
const String _targetPlatformKey = 'targetPlatform';
const String _nameKey = 'name';
@@ -17,16 +17,13 @@ const String _idKey = 'id';
class RunTarget {
/// Construct a RunTarget from a JSON map.
factory RunTarget.fromJson(Map<String, Object> map) {
final List<String> errors = <String>[];
final String name = stringOfJson(map, _nameKey, errors)!;
final String id = stringOfJson(map, _idKey, errors)!;
final String targetPlatform =
stringOfJson(map, _targetPlatformKey, errors)!;
if (errors.isNotEmpty) {
throw FormatException('Failed to parse RunTarget: ${errors.join('\n')}');
}
return RunTarget._(name, id, targetPlatform);
return JsonObject(map).map((JsonObject json) => RunTarget._(
json.string(_nameKey),
json.string(_idKey),
json.string(_targetPlatformKey),
), onError: (JsonObject source, JsonMapException e) {
throw FormatException('Failed to parse RunTarget: $e', source.toPrettyString());
});
}
RunTarget._(this.name, this.id, this.targetPlatform);

View File

@@ -0,0 +1,364 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show JsonEncoder, jsonDecode;
import 'package:meta/meta.dart';
/// A JSON object that contains key-value pairs of other JSON values.
///
/// This extension type provides type-safe access to the values in the
/// underlying JSON object without the need for manual type casting and with
/// helpful APIs for common operations.
///
/// ## Examples
///
/// ### Basic Usage
///
/// ```dart
/// const json = JsonObject({
/// 'name': 'John Doe',
/// 'age': 30,
/// 'isEmployed': true,
/// 'pets': ['Fido', 'Whiskers'],
/// });
///
/// final name = json.string('name');
/// final age = json.integer('age');
/// final isEmployed = json.boolean('isEmployed');
/// final pets = json.stringList('pets');
/// ```
///
/// ### Null Safety
///
/// In the above example, we assumed that all keys exist in the JSON object. To
/// gracefully handle cases where a key may not exist, you can use the `OrNull`
/// variants of the methods:
///
/// ```dart
/// final name = json.stringOrNull('name');
/// ```
///
/// This works nicely with null-aware operators:
///
/// ```dart
/// final name = json.stringOrNull('name') ?? 'Unknown';
/// ```
///
/// ### Bulk Operations
///
/// By default, a [JsonReadException] is thrown if a key is not found or if the
/// value cannot be cast to the expected type, which can be handled using a
/// `try-catch` block:
///
/// ```dart
/// try {
/// final name = json.string('name');
/// } on FormatException catch (e) {
/// print('Error: $e');
/// }
/// ```
///
/// However, it is cumbersome to wrap every access in a `try-catch` block, and
/// sometimes you will want to collect all errors at once. For this, you can use
/// [map] to read multiple values at once and convert them to a custom object:
///
/// ```dart
/// try {
/// final person = json.map(
/// (json) => Person(
/// name: json.string('name'),
/// age: json.integer('age'),
/// isEmployed: json.boolean('isEmployed'),
/// pets: json.stringList('pets'),
/// ),
/// );
/// } on JsonMapException catch (e) {
/// print('Errors: ${e.exceptions}');
/// }
/// ```
///
/// Or, provide an `onError` handler to handle the exception (either to log and
/// provide a default value, or to rethrow a different exception):
///
/// ```dart
/// final person = json.map(
/// (json) => Person(name: json.string('name')),
/// onError: (json, e) => throw FormatException('Failed to read person: $e'),
/// );
/// ```
extension type const JsonObject(Map<String, Object?> _object) {
/// Parses a JSON string into a [JsonObject].
static JsonObject parse(String jsonString) {
return JsonObject(jsonDecode(jsonString) as Map<String, Object?>);
}
// If non-null, errors caught during [map] are stored here.
static List<JsonReadException>? _mapErrors;
// If in the context of a [map] operation, collects exceptions.
// Otherwise, throws the exception.
static void _error(JsonReadException e) {
if (_mapErrors case final List<JsonReadException> list) {
list.add(e);
} else {
throw e;
}
}
T _get<T extends Object>(String key, T defaultTo) {
final T? result = _getOrNull<T>(key);
if (result == null) {
if (!_object.containsKey(key)) {
_error(MissingKeyJsonReadException(this, key));
}
return defaultTo;
}
return result;
}
/// Returns the value at the given [key] as a [String].
///
/// Throws a [JsonReadException] if the value is not found or cannot be cast.
String string(String key) => _get<String>(key, '');
/// Returns the value at the given [key] as an [int].
///
/// Throws a [JsonReadException] if the value is not found or cannot be cast.
int integer(String key) => _get<int>(key, 0);
/// Returns the value at the given [key] as a [bool].
///
/// Throws a [JsonReadException] if the value is not found or cannot be cast.
bool boolean(String key) => _get<bool>(key, false);
List<T> _getList<T extends Object>(String key) {
final List<T>? result = _getListOrNull<T>(key);
if (result == null) {
_error(MissingKeyJsonReadException(this, key));
return <T>[];
}
return result;
}
/// Returns the value at the given [key] as a [List] of [String]s.
///
/// Throws a [JsonReadException] if the value is not found or cannot be cast.
List<String> stringList(String key) => _getList<String>(key);
T? _getOrNull<T extends Object>(String key) {
final Object? value = _object[key];
if (value == null && !_object.containsKey(key)) {
return null;
} else if (value is! T) {
_error(InvalidTypeJsonReadException(
this,
key,
expected: T,
actual: value.runtimeType,
));
return null;
} else {
return value;
}
}
/// Returns the value at the given [key] as a [String].
///
/// If the value is not found, returns `null`.
///
/// Throws a [JsonReadException] if the value cannot be cast.
String? stringOrNull(String key) => _getOrNull<String>(key);
/// Returns the value at the given [key] as an [int].
///
/// If the value is not found, returns `null`.
///
/// Throws a [JsonReadException] if the value cannot be cast.
int? integerOrNull(String key) => _getOrNull<int>(key);
/// Returns the value at the given [key] as a [bool].
///
/// If the value is not found, returns `null`.
///
/// Throws a [JsonReadException] if the value cannot be cast.
bool? booleanOrNull(String key) => _getOrNull<bool>(key);
List<T>? _getListOrNull<T extends Object>(String key) {
final Object? value = _object[key];
if (value == null && !_object.containsKey(key)) {
return null;
} else if (value is! List<Object?>) {
_error(InvalidTypeJsonReadException(
this,
key,
expected: List<T>,
actual: value.runtimeType,
));
return <T>[];
} else {
final List<T> result = <T>[];
for (final Object? element in value) {
if (element is! T) {
_error(InvalidTypeJsonReadException(
this,
key,
expected: T,
actual: element.runtimeType,
));
return <T>[];
}
result.add(element);
}
return result;
}
}
/// Returns the value at the given [key] as a [List] of [String]s.
///
/// If the value is not found, returns `null`.
///
/// Throws a [JsonReadException] if the value cannot be cast.
List<String>? stringListOrNull(String key) => _getListOrNull<String>(key);
static Never _onErrorThrow(JsonObject object, JsonMapException e) {
throw e;
}
/// Returns the result of applying the given [mapper] to this JSON object.
///
/// Any exception that otherwise would be thrown by the mapper is caught
/// internally and rethrown as a [JsonMapException] with all of the original
/// exceptions added to its [exceptions] property.
///
/// If [onError] is provided, it is called with this object and the caught
/// [JsonMapException] to handle the error. If not provided, the exception is
/// rethrown.
///
/// **Note:** The [mapper] function _must_ be synchronous.
///
/// ## Example
///
/// ```dart
/// final person = json.map(
/// (json) => Person(
/// name: json.string('name'),
/// age: json.integer('age'),
/// isEmployed: json.boolean('isEmployed'),
/// ), onError: (json, e) {
/// throw FormatException('Failed to read person: $e');
/// },
/// );
/// ```
T map<T extends Object>(
T Function(JsonObject) mapper, {
T Function(JsonObject, JsonMapException) onError = _onErrorThrow,
}) {
// Refuse asynchronous mappers to avoid reentrancy issues.
//
// Could be replaced with a static check in the future:
// https://github.com/dart-lang/sdk/issues/35024
if (mapper is Future<void> Function(JsonObject)) {
throw ArgumentError.value(
mapper,
'mapper',
'must be synchronous',
);
}
// Store the previous errors, if any.
final List<JsonReadException>? previousErrors = _mapErrors;
// Start collecting errors for this map operation.
final List<JsonReadException> currentErrors = <JsonReadException>[];
_mapErrors = currentErrors;
try {
final T result = mapper(this);
if (currentErrors.isEmpty) {
return result;
} else {
return onError(this, JsonMapException(this, currentErrors));
}
} finally {
// Restore the previous errors.
_mapErrors = previousErrors;
}
}
/// Returns a "pretty" JSON representation of this object.
String toPrettyString() {
return const JsonEncoder.withIndent(' ').convert(_object);
}
}
/// An exception thrown when a JSON value cannot be read as the expected type.
sealed class JsonReadException implements Exception {
const JsonReadException(this.object);
/// The JSON object that was being read.
final JsonObject object;
@override
@mustBeOverridden
String toString();
}
/// An exception thrown when read exceptions occur during [JsonObject.map].
final class JsonMapException extends JsonReadException {
/// Creates an exception for multiple JSON read exceptions.
///
/// If [exceptions] is empty, a [StateError] is thrown.
JsonMapException(super.object, Iterable<JsonReadException> exceptions)
: exceptions = List<JsonReadException>.unmodifiable(exceptions) {
if (exceptions.isEmpty) {
throw StateError('Must provide at least one exception.');
}
}
/// The list of exceptions that occurred while mapping the JSON object.
final List<JsonReadException> exceptions;
@override
String toString() {
return 'Failed to read object:\n\n${exceptions.join('\n')}';
}
}
/// An exception thrown when a JSON [key] is not found in the JSON object.
final class MissingKeyJsonReadException extends JsonReadException {
/// Creates an exception for a missing key in a JSON object.
const MissingKeyJsonReadException(super.object, this.key);
/// The key that was being read.
final String key;
@override
String toString() => 'Key "$key" not found.';
}
/// An exception thrown when a JSON [key] is found but the value cannot be cast.
final class InvalidTypeJsonReadException extends JsonReadException {
/// Creates an exception for an invalid type in a JSON object.
const InvalidTypeJsonReadException(
super.object,
this.key, {
required this.expected,
required this.actual,
});
/// The key that was being read.
final String key;
/// The expected type of the value.
final Type expected;
/// The actual type of the value.
final Type actual;
@override
String toString() {
return 'Key "$key" expected type: $expected, actual type: $actual.';
}
}

View File

@@ -5,7 +5,8 @@
name: engine_tool
publish_to: none
environment:
sdk: '>=3.2.0-0 <4.0.0'
# Required for extension types.
sdk: ^3.3.0
# Do not add any dependencies that require more than what is provided in
# //third_party/pkg, //third_party/dart/pkg, or

View File

@@ -0,0 +1,264 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:engine_tool/src/typed_json.dart';
import 'package:litetest/litetest.dart';
void main() {
group('JsonObject.string', () {
test('returns string value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(jsonObject.string('key'), 'value');
});
test('throws due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(() => jsonObject.string('missing'), throwsA(isInstanceOf<MissingKeyJsonReadException>()));
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 42});
expect(() => jsonObject.string('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.integer', () {
test('returns integer value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 42});
expect(jsonObject.integer('key'), 42);
});
test('throws due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 42});
expect(() => jsonObject.integer('missing'), throwsA(isInstanceOf<MissingKeyJsonReadException>()));
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(() => jsonObject.integer('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.boolean', () {
test('returns boolean value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': true});
expect(jsonObject.boolean('key'), true);
});
test('throws due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': true});
expect(() => jsonObject.boolean('missing'), throwsA(isInstanceOf<MissingKeyJsonReadException>()));
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(() => jsonObject.boolean('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.stringList', () {
test('returns string list value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': <Object?>['value1', 'value2']});
expect(jsonObject.stringList('key'), <String>['value1', 'value2']);
});
test('throws due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': <Object?>['value1', 'value2']});
expect(() => jsonObject.stringList('missing'), throwsA(isInstanceOf<MissingKeyJsonReadException>()));
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(() => jsonObject.stringList('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
test('throws due to wrong element type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': <Object?>['value1', 42]});
expect(() => jsonObject.stringList('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.stringOrNull', () {
test('returns string value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(jsonObject.stringOrNull('key'), 'value');
});
test('returns null due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(jsonObject.stringOrNull('missing'), isNull);
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 42});
expect(() => jsonObject.stringOrNull('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.integerOrNull', () {
test('returns integer value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 42});
expect(jsonObject.integerOrNull('key'), 42);
});
test('returns null due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 42});
expect(jsonObject.integerOrNull('missing'), isNull);
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(() => jsonObject.integerOrNull('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.booleanOrNull', () {
test('returns boolean value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': true});
expect(jsonObject.booleanOrNull('key'), true);
});
test('returns null due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': true});
expect(jsonObject.booleanOrNull('missing'), isNull);
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(() => jsonObject.booleanOrNull('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.stringListOrNull', () {
test('returns string list value', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': <Object?>['value1', 'value2']});
expect(jsonObject.stringListOrNull('key'), <String>['value1', 'value2']);
});
test('returns null due to missing key', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': <Object?>['value1', 'value2']});
expect(jsonObject.stringListOrNull('missing'), isNull);
});
test('throws due to wrong type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': 'value'});
expect(() => jsonObject.stringListOrNull('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
test('throws due to wrong element type', () {
const JsonObject jsonObject = JsonObject(<String, Object?>{'key': <Object?>['value1', 42]});
expect(() => jsonObject.stringListOrNull('key'), throwsA(isInstanceOf<InvalidTypeJsonReadException>()));
});
});
group('JsonObject.map', () {
test('returns multiple fields', () {
final (String name, int age, bool isStudent) = const JsonObject(<String, Object?>{
'name': 'Alice',
'age': 42,
'isStudent': true,
}).map((JsonObject json) {
return (
json.string('name'),
json.integer('age'),
json.boolean('isStudent'),
);
});
expect(name, 'Alice');
expect(age, 42);
expect(isStudent, true);
});
test('throws due to missing keys', () {
try {
const JsonObject(<String, Object?>{
'age': 42,
}).map((JsonObject json) {
return (
json.string('name'),
json.integer('age'),
json.boolean('isStudent'),
);
});
fail('Expected JsonMapException');
} on JsonMapException catch (e) {
expect(
e.exceptions.map((JsonReadException e) => (e as MissingKeyJsonReadException).key).toList(),
containsStringsInOrder(<String>['name', 'isStudent'],
));
}
});
test('throws due to wrong types', () {
try {
const JsonObject(<String, Object?>{
'name': 42,
'age': '42',
'isStudent': false,
}).map((JsonObject json) {
return (
json.string('name'),
json.integer('age'),
json.boolean('isStudent'),
);
});
fail('Expected JsonMapException');
} on JsonMapException catch (e) {
expect(
e.exceptions.map((JsonReadException e) => switch (e) {
final InvalidTypeJsonReadException e => e.key,
final MissingKeyJsonReadException e => e.key,
_ => throw StateError('Unexpected exception type: $e'),
}).toList(),
containsStringsInOrder(<String>['name', 'age'],
));
}
});
test('allows a default with onError', () {
final (String name, int age, bool isStudent) = const JsonObject(<String, Object?>{
'name': 'Alice',
'age': 42,
'isStudent': 'true',
}).map((JsonObject json) {
return (
json.string('name'),
json.integer('age'),
json.boolean('isStudent'),
);
}, onError: expectAsync2((_, JsonMapException e) {
expect(
e.exceptions.map((JsonReadException e) => switch (e) {
final InvalidTypeJsonReadException e => e.key,
final MissingKeyJsonReadException e => e.key,
_ => throw StateError('Unexpected exception type: $e'),
}).toList(),
<String>['isStudent'],
);
return ('Bob', 0, false);
}));
expect(name, 'Bob');
expect(age, 0);
expect(isStudent, false);
});
test('disallows a return type of Future<*>', () {
expect(() {
const JsonObject(<String, Object?>{
'name': 'Alice',
'age': 42,
'isStudent': true,
}).map((JsonObject json) async {
return (
json.string('name'),
json.integer('age'),
json.boolean('isStudent'),
);
});
}, throwsA(isInstanceOf<ArgumentError>()));
});
});
}