From f7af4c573b27a7bec3164b966c95eab11b554bbe Mon Sep 17 00:00:00 2001 From: minnu <121003219@sastra.ac.in> Date: Thu, 1 Apr 2021 16:54:18 +0530 Subject: [PATCH] Added lint rules --- analysis_options.yaml | 35 +++ example/generate_model_example.dart | 18 +- example/generate_model_private_example.dart | 18 +- lib/helpers.dart | 134 +++++------ lib/model_generator.dart | 85 +++---- lib/syntax.dart | 247 ++++++++++---------- lib/warning.dart | 4 +- pubspec.yaml | 6 +- test/array_root_test.dart | 21 +- test/bug_10_test.dart | 108 +++++---- test/bug_39_test.dart | 18 +- test/bug_40_test.dart | 25 +- test/double_test.dart | 32 +-- test/generated/bug_ten.dart | 44 ++-- test/generated/sample.dart | 47 ++-- test/generated/sample_private.dart | 102 ++++---- test/helpers_test.dart | 16 +- test/matrix_test.dart | 18 +- test/model_generator_private_test.dart | 88 +++---- test/model_generator_test.dart | 84 +++---- test/model_generator_warnings_test.dart | 34 +-- 21 files changed, 606 insertions(+), 578 deletions(-) create mode 100644 analysis_options.yaml diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..d01aa3d --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,35 @@ +analyzer: + errors: + unused_local_variable: ignore + invalid_assignment: warning + missing_return: error + dead_code: warning + +linter: + rules: + avoid_type_to_string: true + avoid_slow_async_io: true + camel_case_types: true + empty_constructor_bodies: true + prefer_const_constructors: true + sort_constructors_first: true + prefer_single_quotes: true + lines_longer_than_80_chars: true + avoid_empty_else: true + cancel_subscriptions: true + close_sinks: true + prefer_conditional_assignment: true + cast_nullable_to_non_nullable: true + null_check_on_nullable_type_parameter: true + always_specify_types: true + prefer_null_aware_operators: true + avoid_returning_null_for_future: true + unnecessary_nullable_for_final_variable_declarations: true + always_declare_return_types: true + avoid_returning_null: true + avoid_returning_null_for_void: true + avoid_returning_this: true + avoid_void_async: true + prefer_expression_function_bodies: true + unnecessary_await_in_return: true + unnecessary_final: true \ No newline at end of file diff --git a/example/generate_model_example.dart b/example/generate_model_example.dart index 3aba696..b716851 100644 --- a/example/generate_model_example.dart +++ b/example/generate_model_example.dart @@ -1,23 +1,23 @@ import 'dart:io'; -import "package:path/path.dart" show dirname, join, normalize; +import 'package:path/path.dart' show dirname, join, normalize; import '../lib/json_to_dart.dart'; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } -main() { - final classGenerator = new ModelGenerator('Sample'); - final currentDirectory = dirname(_scriptPath()); - final filePath = normalize(join(currentDirectory, 'sample.json')); - final jsonRawData = new File(filePath).readAsStringSync(); +void main() { + ModelGenerator classGenerator = new ModelGenerator('Sample'); + String currentDirectory = dirname(_scriptPath()); + String filePath = normalize(join(currentDirectory, 'sample.json')); + String jsonRawData = new File(filePath).readAsStringSync(); DartCode dartCode = classGenerator.generateDartClasses(jsonRawData); print(dartCode.code); } diff --git a/example/generate_model_private_example.dart b/example/generate_model_private_example.dart index 35b85c2..d593e16 100644 --- a/example/generate_model_private_example.dart +++ b/example/generate_model_private_example.dart @@ -1,23 +1,23 @@ import 'dart:io'; -import "package:path/path.dart" show dirname, join, normalize; +import 'package:path/path.dart' show dirname, join, normalize; import '../lib/json_to_dart.dart'; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } -main() { - final classGenerator = new ModelGenerator('Sample', true); - final currentDirectory = dirname(_scriptPath()); - final filePath = normalize(join(currentDirectory, 'sample.json')); - final jsonRawData = new File(filePath).readAsStringSync(); +void main() { + ModelGenerator classGenerator = new ModelGenerator('Sample', true); + String currentDirectory = dirname(_scriptPath()); + String filePath = normalize(join(currentDirectory, 'sample.json')); + String jsonRawData = new File(filePath).readAsStringSync(); DartCode dartCode = classGenerator.generateDartClasses(jsonRawData); print(dartCode.code); } diff --git a/lib/helpers.dart b/lib/helpers.dart index d3d8c60..3607b57 100644 --- a/lib/helpers.dart +++ b/lib/helpers.dart @@ -2,9 +2,10 @@ import 'dart:convert' as Convert; import 'dart:math'; import 'package:json_ast/json_ast.dart' show Node, ObjectNode, ArrayNode, LiteralNode; +import 'package:json_ast/tokenize.dart'; import 'package:json_to_dart/syntax.dart'; -const Map PRIMITIVE_TYPES = const { +const Map PRIMITIVE_TYPES = const { 'int': true, 'double': true, 'String': true, @@ -21,16 +22,15 @@ const Map PRIMITIVE_TYPES = const { enum ListType { Object, String, Double, Int, Null } class MergeableListType { + MergeableListType(this.listType, this.isAmbigous); final ListType listType; final bool isAmbigous; - - MergeableListType(this.listType, this.isAmbigous); } MergeableListType mergeableListType(List list) { ListType t = ListType.Null; bool isAmbigous = false; - list.forEach((e) { + list.forEach((dynamic e) { ListType inferredType; if (e.runtimeType == 'int') { inferredType = ListType.Int; @@ -52,31 +52,30 @@ MergeableListType mergeableListType(List list) { String camelCase(String text) { String capitalize(Match m) => m[0].substring(0, 1).toUpperCase() + m[0].substring(1); - String skip(String s) => ""; + String skip(String s) => ''; return text.splitMapJoin(new RegExp(r'[a-zA-Z0-9]+'), onMatch: capitalize, onNonMatch: skip); } String camelCaseFirstLower(String text) { - final camelCaseText = camelCase(text); - final firstChar = camelCaseText.substring(0, 1).toLowerCase(); - final rest = camelCaseText.substring(1); + String camelCaseText = camelCase(text); + String firstChar = camelCaseText.substring(0, 1).toLowerCase(); + String rest = camelCaseText.substring(1); return '$firstChar$rest'; } -decodeJSON(String rawJson) { - return Convert.json.decode(rawJson); -} +dynamic decodeJSON(String rawJson) => Convert.json.decode(rawJson); -WithWarning mergeObj(Map obj, Map other, String path) { - List warnings = new List(); - final Map clone = Map.from(obj); - other.forEach((k, v) { +WithWarning> mergeObj( + Map obj, Map other, String path) { + List warnings = []; + Map clone = Map.from(obj); + other.forEach((dynamic k, dynamic v) { if (clone[k] == null) { clone[k] = v; } else { - final String otherType = getTypeName(v); - final String t = getTypeName(clone[k]); + String otherType = getTypeName(v); + String t = getTypeName(clone[k]); if (t != otherType) { if (t == 'int' && otherType == 'double') { // if double was found instead of int, assign the double @@ -86,44 +85,49 @@ WithWarning mergeObj(Map obj, Map other, String path) { warnings.add(newAmbiguousType('$path/$k')); } } else if (t == 'List') { - List l = List.from(clone[k]); + List l = List.from(clone[k]); l.addAll(other[k]); - final mergeableType = mergeableListType(l); + MergeableListType mergeableType = mergeableListType(l); if (ListType.Object == mergeableType.listType) { - WithWarning mergedList = mergeObjectList(l, '$path'); + WithWarning> mergedList = + mergeObjectList(l, '$path'); warnings.addAll(mergedList.warnings); - clone[k] = List.filled(1, mergedList.result); + clone[k] = List>.filled(1, mergedList.result); } else { if (l.length > 0) { - clone[k] = List.filled(1, l[0]); + clone[k] = List>.filled(1, l[0]); } if (mergeableType.isAmbigous) { warnings.add(newAmbiguousType('$path/$k')); } } } else if (t == 'Class') { - WithWarning mergedObj = mergeObj(clone[k], other[k], '$path/$k'); + WithWarning> mergedObj = + mergeObj(clone[k], other[k], '$path/$k'); warnings.addAll(mergedObj.warnings); clone[k] = mergedObj.result; } } }); - return new WithWarning(clone, warnings); + return new WithWarning>(clone, warnings); } -WithWarning mergeObjectList(List list, String path, +WithWarning> mergeObjectList( + List list, String path, [int idx = -1]) { - List warnings = new List(); - Map obj = new Map(); - for (var i = 0; i < list.length; i++) { - final toMerge = list[i]; + List warnings = []; + Map obj = new Map(); + for (int i = 0; i < list.length; i++) { + dynamic toMerge = list[i]; if (toMerge is Map) { - toMerge.forEach((k, v) { - final String t = getTypeName(obj[k]); + toMerge.forEach((dynamic k, dynamic v) { + assert(v != null); + assert(k != null); + String t = getTypeName(obj[k]); if (obj[k] == null) { obj[k] = v; } else { - final String otherType = getTypeName(v); + String otherType = getTypeName(v); if (t != otherType) { if (t == 'int' && otherType == 'double') { // if double was found instead of int, assign the double @@ -134,23 +138,23 @@ WithWarning mergeObjectList(List list, String path, if (idx != -1) { realIndex = idx - i; } - final String ambiguosTypePath = '$path[$realIndex]/$k'; + String ambiguosTypePath = '$path[$realIndex]/$k'; warnings.add(newAmbiguousType(ambiguosTypePath)); } } else if (t == 'List') { - List l = List.from(obj[k]); - final int beginIndex = l.length; + List l = List.from(obj[k]); + int beginIndex = l.length; l.addAll(v); // bug is here - final mergeableType = mergeableListType(l); + MergeableListType mergeableType = mergeableListType(l); if (ListType.Object == mergeableType.listType) { - WithWarning mergedList = + WithWarning> mergedList = mergeObjectList(l, '$path[$i]/$k', beginIndex); warnings.addAll(mergedList.warnings); - obj[k] = List.filled(1, mergedList.result); + obj[k] = List.filled(1, mergedList.result); } else { if (l.length > 0) { - obj[k] = List.filled(1, l[0]); + obj[k] = List.filled(1, l[0]); } if (mergeableType.isAmbigous) { warnings.add(newAmbiguousType('$path[$i]/$k')); @@ -161,7 +165,7 @@ WithWarning mergeObjectList(List list, String path, if (idx != -1) { properIndex = i - idx; } - WithWarning mergedObj = mergeObj( + WithWarning> mergedObj = mergeObj( obj[k], v, '$path[$properIndex]/$k', @@ -173,11 +177,11 @@ WithWarning mergeObjectList(List list, String path, }); } } - return new WithWarning(obj, warnings); + return new WithWarning>(obj, warnings); } -isPrimitiveType(String typeName) { - final isPrimitive = PRIMITIVE_TYPES[typeName]; +bool isPrimitiveType(String typeName) { + bool isPrimitive = PRIMITIVE_TYPES[typeName]; if (isPrimitive == null) { return false; } @@ -186,12 +190,12 @@ isPrimitiveType(String typeName) { String fixFieldName(String name, {TypeDefinition typeDef, bool privateField = false}) { - var properName = name; + String properName = name; if (name.startsWith('_') || name.startsWith(new RegExp(r'[0-9]'))) { - final firstCharType = typeDef.name.substring(0, 1).toLowerCase(); + String firstCharType = typeDef.name.substring(0, 1).toLowerCase(); properName = '$firstCharType$name'; } - final fieldName = camelCaseFirstLower(properName); + String fieldName = camelCaseFirstLower(properName); if (privateField) { return '_$fieldName'; } @@ -220,19 +224,17 @@ String getTypeName(dynamic obj) { Node navigateNode(Node astNode, String path) { Node node; if (astNode is ObjectNode) { - final ObjectNode objectNode = astNode; - final propertyNode = objectNode.children.firstWhere((final prop) { - return prop.key.value == path; - }, orElse: () { - return null; - }); + ObjectNode objectNode = astNode; + PropertyNode propertyNode = objectNode.children.firstWhere( + (PropertyNode prop) => prop.key.value == path, + orElse: () => null); if (propertyNode != null) { node = propertyNode.value; } } if (astNode is ArrayNode) { - final ArrayNode arrayNode = astNode; - final index = int.tryParse(path) ?? null; + ArrayNode arrayNode = astNode; + int index = int.tryParse(path) ?? null; if (index != null && arrayNode.children.length > index) { node = arrayNode.children[index]; } @@ -240,21 +242,21 @@ Node navigateNode(Node astNode, String path) { return node; } -final _pattern = RegExp(r"([0-9]+)\.{0,1}([0-9]*)e(([-0-9]+))"); +final RegExp _pattern = RegExp(r'([0-9]+)\.{0,1}([0-9]*)e(([-0-9]+))'); bool isASTLiteralDouble(Node astNode) { if (astNode != null && astNode is LiteralNode) { - final LiteralNode literalNode = astNode; - final containsPoint = literalNode.raw.contains('.'); - final containsExponent = literalNode.raw.contains('e'); + LiteralNode literalNode = astNode; + bool containsPoint = literalNode.raw.contains('.'); + bool containsExponent = literalNode.raw.contains('e'); if (containsPoint || containsExponent) { - var isDouble = containsPoint; + bool isDouble = containsPoint; if (containsExponent) { - final matches = _pattern.firstMatch(literalNode.raw); + RegExpMatch matches = _pattern.firstMatch(literalNode.raw); if (matches != null) { - final integer = matches[1]; - final comma = matches[2]; - final exponent = matches[3]; + String integer = matches[1]; + String comma = matches[2]; + String exponent = matches[3]; isDouble = _isDoubleWithExponential(integer, comma, exponent); } } @@ -265,9 +267,9 @@ bool isASTLiteralDouble(Node astNode) { } bool _isDoubleWithExponential(String integer, String comma, String exponent) { - final integerNumber = int.tryParse(integer) ?? 0; - final exponentNumber = int.tryParse(exponent) ?? 0; - final commaNumber = int.tryParse(comma) ?? 0; + int integerNumber = int.tryParse(integer) ?? 0; + int exponentNumber = int.tryParse(exponent) ?? 0; + int commaNumber = int.tryParse(comma) ?? 0; if (exponentNumber != null) { if (exponentNumber == 0) { return commaNumber > 0; diff --git a/lib/model_generator.dart b/lib/model_generator.dart index 31f45f6..8ccc121 100644 --- a/lib/model_generator.dart +++ b/lib/model_generator.dart @@ -13,47 +13,45 @@ class DartCode extends WithWarning { /// A Hint is a user type correction. class Hint { + Hint(this.path, this.type); final String path; final String type; - - Hint(this.path, this.type); } class ModelGenerator { - final String _rootClassName; - final bool _privateFields; - List allClasses = new List(); - final Map sameClassMapping = new HashMap(); - List hints; - - ModelGenerator(this._rootClassName, [this._privateFields = false, hints]) { + ModelGenerator(this._rootClassName, + [this._privateFields = false, this.hints]) { if (hints != null) { this.hints = hints; } else { - this.hints = new List(); + this.hints = []; } } + final String _rootClassName; + final bool _privateFields; + List allClasses = []; + final Map sameClassMapping = new HashMap(); + List hints; - Hint _hintForPath(String path) { - return this.hints.firstWhere((h) => h.path == path, orElse: () => null); - } + Hint _hintForPath(String path) => + this.hints.firstWhere((Hint h) => h.path == path, orElse: () => null); List _generateClassDefinition( String className, dynamic jsonRawDynamicData, String path, Node astNode) { - List warnings = new List(); + List warnings = []; if (jsonRawDynamicData is List) { // if first element is an array, start in the first element. - final node = navigateNode(astNode, '0'); + Node node = navigateNode(astNode, '0'); _generateClassDefinition(className, jsonRawDynamicData[0], path, node); } else { - final Map jsonRawData = jsonRawDynamicData; - final keys = jsonRawData.keys; + Map jsonRawData = jsonRawDynamicData; + Iterable keys = jsonRawData.keys; ClassDefinition classDefinition = new ClassDefinition(className, _privateFields); - keys.forEach((key) { + keys.forEach((dynamic key) { TypeDefinition typeDef; - final hint = _hintForPath('$path/$key'); - final node = navigateNode(astNode, key); + Hint hint = _hintForPath('$path/$key'); + Node node = navigateNode(astNode, key); if (hint != null) { typeDef = new TypeDefinition(hint.type, astNode: node); } else { @@ -73,38 +71,41 @@ class ModelGenerator { } classDefinition.addField(key, typeDef); }); - final similarClass = allClasses.firstWhere((cd) => cd == classDefinition, + ClassDefinition similarClass = allClasses.firstWhere( + (ClassDefinition cd) => cd == classDefinition, orElse: () => null); if (similarClass != null) { - final similarClassName = similarClass.name; - final currentClassName = classDefinition.name; + String similarClassName = similarClass.name; + String currentClassName = classDefinition.name; sameClassMapping[currentClassName] = similarClassName; } else { allClasses.add(classDefinition); } - final dependencies = classDefinition.dependencies; - dependencies.forEach((dependency) { + List dependencies = classDefinition.dependencies; + dependencies.forEach((Dependency dependency) { List warns; if (dependency.typeDef.name == 'List') { // only generate dependency class if the array is not empty if (jsonRawData[dependency.name].length > 0) { - // when list has ambiguous values, take the first one, otherwise merge all objects + // when list has ambiguous values, + // take the first one, otherwise merge all objects // into a single one dynamic toAnalyze; if (!dependency.typeDef.isAmbiguous) { - WithWarning mergeWithWarning = mergeObjectList( - jsonRawData[dependency.name], '$path/${dependency.name}'); + WithWarning> mergeWithWarning = + mergeObjectList( + jsonRawData[dependency.name], '$path/${dependency.name}'); toAnalyze = mergeWithWarning.result; warnings.addAll(mergeWithWarning.warnings); } else { toAnalyze = jsonRawData[dependency.name][0]; } - final node = navigateNode(astNode, dependency.name); + Node node = navigateNode(astNode, dependency.name); warns = _generateClassDefinition(dependency.className, toAnalyze, '$path/${dependency.name}', node); } } else { - final node = navigateNode(astNode, dependency.name); + Node node = navigateNode(astNode, dependency.name); warns = _generateClassDefinition(dependency.className, jsonRawData[dependency.name], '$path/${dependency.name}', node); } @@ -121,30 +122,32 @@ class ModelGenerator { /// formatted JSON string. The dart code is not validated so invalid dart code /// might be returned DartCode generateUnsafeDart(String rawJson) { - final jsonRawData = decodeJSON(rawJson); - final astNode = parse(rawJson, Settings()); + dynamic jsonRawData = decodeJSON(rawJson); + Node astNode = parse(rawJson, Settings()); List warnings = - _generateClassDefinition(_rootClassName, jsonRawData, "", astNode); + _generateClassDefinition(_rootClassName, jsonRawData, '', astNode); // after generating all classes, replace the omited similar classes. - allClasses.forEach((c) { - final fieldsKeys = c.fields.keys; - fieldsKeys.forEach((f) { - final typeForField = c.fields[f]; + allClasses.forEach((ClassDefinition c) { + Iterable fieldsKeys = c.fields.keys; + fieldsKeys.forEach((String f) { + TypeDefinition typeForField = c.fields[f]; if (sameClassMapping.containsKey(typeForField.name)) { c.fields[f].name = sameClassMapping[typeForField.name]; } }); }); return new DartCode( - allClasses.map((c) => c.toString()).join('\n'), warnings); + allClasses.map((ClassDefinition c) => c.toString()).join('\n'), + warnings); } /// generateDartClasses will generate all classes and append one after another /// in a single string. The [rawJson] param is assumed to be a properly - /// formatted JSON string. If the generated dart is invalid it will throw an error. + /// formatted JSON string. + /// If the generated dart is invalid it will throw an error. DartCode generateDartClasses(String rawJson) { - final unsafeDartCode = generateUnsafeDart(rawJson); - final formatter = new DartFormatter(); + DartCode unsafeDartCode = generateUnsafeDart(rawJson); + DartFormatter formatter = new DartFormatter(); return new DartCode( formatter.format(unsafeDartCode.code), unsafeDartCode.warnings); } diff --git a/lib/syntax.dart b/lib/syntax.dart index d4571f8..b8d5788 100644 --- a/lib/syntax.dart +++ b/lib/syntax.dart @@ -1,45 +1,50 @@ import 'package:json_ast/json_ast.dart' show Node; import 'package:json_to_dart/helpers.dart'; -const String emptyListWarn = "list is empty"; -const String ambiguousListWarn = "list is ambiguous"; -const String ambiguousTypeWarn = "type is ambiguous"; +const String emptyListWarn = 'list is empty'; +const String ambiguousListWarn = 'list is ambiguous'; +const String ambiguousTypeWarn = 'type is ambiguous'; class Warning { + Warning(this.warning, this.path); final String warning; final String path; - - Warning(this.warning, this.path); } -Warning newEmptyListWarn(String path) { - return new Warning(emptyListWarn, path); -} +Warning newEmptyListWarn(String path) => new Warning(emptyListWarn, path); -Warning newAmbiguousListWarn(String path) { - return new Warning(ambiguousListWarn, path); -} +Warning newAmbiguousListWarn(String path) => + new Warning(ambiguousListWarn, path); -Warning newAmbiguousType(String path) { - return new Warning(ambiguousTypeWarn, path); -} +Warning newAmbiguousType(String path) => new Warning(ambiguousTypeWarn, path); class WithWarning { + WithWarning(this.result, this.warnings); final T result; final List warnings; - - WithWarning(this.result, this.warnings); } class TypeDefinition { - String name; - String subtype; - bool isAmbiguous = false; - bool _isPrimitive = false; + TypeDefinition( + this.name, { + this.subtype, + this.isAmbiguous, + Node astNode, + }) { + if (subtype == null) { + _isPrimitive = isPrimitiveType(this.name); + if (this.name == 'int' && isASTLiteralDouble(astNode)) { + this.name = 'double'; + } + } else { + _isPrimitive = isPrimitiveType('$name<$subtype>'); + } + isAmbiguous ??= false; + } factory TypeDefinition.fromDynamic(dynamic obj, Node astNode) { bool isAmbiguous = false; - final type = getTypeName(obj); + String type = getTypeName(obj); if (type == 'List') { List list = obj; String elemType; @@ -53,29 +58,19 @@ class TypeDefinition { } } else { // when array is empty insert Null just to warn the user - elemType = "Null"; + elemType = 'Null'; } return new TypeDefinition(type, astNode: astNode, subtype: elemType, isAmbiguous: isAmbiguous); } return new TypeDefinition(type, astNode: astNode, isAmbiguous: isAmbiguous); } + String name; + String subtype; + bool isAmbiguous = false; + bool _isPrimitive = false; - TypeDefinition(this.name, {this.subtype, this.isAmbiguous, Node astNode}) { - if (subtype == null) { - _isPrimitive = isPrimitiveType(this.name); - if (this.name == 'int' && isASTLiteralDouble(astNode)) { - this.name = 'double'; - } - } else { - _isPrimitive = isPrimitiveType('$name<$subtype>'); - } - if (isAmbiguous == null) { - isAmbiguous = false; - } - } - - bool operator ==(other) { + bool operator ==(dynamic other) { if (other is TypeDefinition) { TypeDefinition otherTypeDef = other; return this.name == otherTypeDef.name && @@ -91,66 +86,67 @@ class TypeDefinition { bool get isPrimitiveList => _isPrimitive && name == 'List'; String _buildParseClass(String expression) { - final properType = subtype != null ? subtype : name; + String properType = subtype != null ? subtype : name; return 'new $properType.fromJson($expression)'; } - String _buildToJsonClass(String expression) { - return '$expression.toJson()'; - } + String _buildToJsonClass(String expression) => '$expression.toJson()'; String jsonParseExpression(String key, bool privateField) { - final jsonKey = "json['$key']"; - final fieldKey = + String jsonKey = "json['$key']"; + String fieldKey = fixFieldName(key, typeDef: this, privateField: privateField); if (isPrimitive) { - if (name == "List") { + if (name == 'List') { return "$fieldKey = json['$key'].cast<$subtype>();"; } return "$fieldKey = json['$key'];"; - } else if (name == "List" && subtype == "DateTime") { + } else if (name == 'List' && subtype == 'DateTime') { return "$fieldKey = json['$key'].map((v) => DateTime.tryParse(v));"; - } else if (name == "DateTime") { + } else if (name == 'DateTime') { return "$fieldKey = DateTime.tryParse(json['$key']);"; } else if (name == 'List') { // list of class - return "if (json['$key'] != null) {\n\t\t\t$fieldKey = new List<$subtype>();\n\t\t\tjson['$key'].forEach((v) { $fieldKey.add(new $subtype.fromJson(v)); });\n\t\t}"; + return ''' +if (json['$key'] != null) {\n\t\t\t$fieldKey = new List<$subtype>();\n\t\t\tjson['$key'].forEach((v) { $fieldKey.add(new $subtype.fromJson(v)); });\n\t\t}'''; } else { // class - return "$fieldKey = json['$key'] != null ? ${_buildParseClass(jsonKey)} : null;"; + return ''' +$fieldKey = json['$key'] != null ? ${_buildParseClass(jsonKey)} : null;'''; } } String toJsonExpression(String key, bool privateField) { - final fieldKey = + String fieldKey = fixFieldName(key, typeDef: this, privateField: privateField); - final thisKey = 'this.$fieldKey'; + String thisKey = 'this.$fieldKey'; if (isPrimitive) { - return "data['$key'] = $thisKey;"; + return ''' +data['$key'] = $thisKey;'''; } else if (name == 'List') { // class list - return """if ($thisKey != null) { + return '''if ($thisKey != null) { data['$key'] = $thisKey.map((v) => ${_buildToJsonClass('v')}).toList(); - }"""; + }'''; } else { // class - return """if ($thisKey != null) { + return '''if ($thisKey != null) { data['$key'] = ${_buildToJsonClass(thisKey)}; - }"""; + }'''; } } } class Dependency { + Dependency(this.name, this.typeDef); String name; final TypeDefinition typeDef; - Dependency(this.name, this.typeDef); - String get className => camelCase(name); } class ClassDefinition { + ClassDefinition(this._name, [this._privateFields = false]); final String _name; final bool _privateFields; final Map fields = new Map(); @@ -159,10 +155,10 @@ class ClassDefinition { bool get privateFields => _privateFields; List get dependencies { - final dependenciesList = new List(); - final keys = fields.keys; - keys.forEach((k) { - final f = fields[k]; + List dependenciesList = []; + Iterable keys = fields.keys; + keys.forEach((String k) { + TypeDefinition f = fields[k]; if (!f.isPrimitive) { dependenciesList.add(new Dependency(k, f)); } @@ -170,9 +166,8 @@ class ClassDefinition { return dependenciesList; } - ClassDefinition(this._name, [this._privateFields = false]); - - bool operator ==(other) { + bool operator ==(dynamic other) { + assert(other != null); if (other is ClassDefinition) { ClassDefinition otherClassDef = other; return this.isSubsetOf(otherClassDef) && otherClassDef.isSubsetOf(this); @@ -181,8 +176,8 @@ class ClassDefinition { } bool isSubsetOf(ClassDefinition other) { - final List keys = this.fields.keys.toList(); - final int len = keys.length; + List keys = this.fields.keys.toList(); + int len = keys.length; for (int i = 0; i < len; i++) { TypeDefinition otherTypeDef = other.fields[keys[i]]; if (otherTypeDef != null) { @@ -197,15 +192,13 @@ class ClassDefinition { return true; } - hasField(TypeDefinition otherField) { - return fields.keys - .firstWhere((k) => fields[k] == otherField, orElse: () => null) != - null; - } + bool hasField(TypeDefinition otherField) => + fields.keys.firstWhere((String k) => fields[k] == otherField, + orElse: () => null) != + null; - addField(String name, TypeDefinition typeDef) { - fields[name] = typeDef; - } + TypeDefinition addField(String name, TypeDefinition typeDef) => + fields[name] = typeDef; void _addTypeDef(TypeDefinition typeDef, StringBuffer sb) { sb.write('${typeDef.name}'); @@ -214,45 +207,41 @@ class ClassDefinition { } } - String get _fieldList { - return fields.keys.map((key) { - final f = fields[key]; - final fieldName = - fixFieldName(key, typeDef: f, privateField: privateFields); - final sb = new StringBuffer(); - sb.write('\t'); - _addTypeDef(f, sb); - sb.write(' $fieldName;'); - return sb.toString(); - }).join('\n'); - } - - String get _gettersSetters { - return fields.keys.map((key) { - final f = fields[key]; - final publicFieldName = - fixFieldName(key, typeDef: f, privateField: false); - final privateFieldName = - fixFieldName(key, typeDef: f, privateField: true); - final sb = new StringBuffer(); - sb.write('\t'); - _addTypeDef(f, sb); - sb.write( - ' get $publicFieldName => $privateFieldName;\n\tset $publicFieldName('); - _addTypeDef(f, sb); - sb.write(' $publicFieldName) => $privateFieldName = $publicFieldName;'); - return sb.toString(); - }).join('\n'); - } + String get _fieldList => fields.keys.map((String key) { + TypeDefinition f = fields[key]; + String fieldName = + fixFieldName(key, typeDef: f, privateField: privateFields); + StringBuffer sb = new StringBuffer(); + sb.write('\t'); + _addTypeDef(f, sb); + sb.write(' $fieldName;'); + return sb.toString(); + }).join('\n'); + + String get _gettersSetters => fields.keys.map((String key) { + TypeDefinition f = fields[key]; + String publicFieldName = + fixFieldName(key, typeDef: f, privateField: false); + String privateFieldName = + fixFieldName(key, typeDef: f, privateField: true); + StringBuffer sb = new StringBuffer(); + sb.write('\t'); + _addTypeDef(f, sb); + sb.write(''' + get $publicFieldName => $privateFieldName;\n\tset $publicFieldName('''); + _addTypeDef(f, sb); + sb.write(' $publicFieldName) => $privateFieldName = $publicFieldName;'); + return sb.toString(); + }).join('\n'); String get _defaultPrivateConstructor { - final sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.write('\t$name({'); - var i = 0; - var len = fields.keys.length - 1; - fields.keys.forEach((key) { - final f = fields[key]; - final publicFieldName = + int i = 0; + int len = fields.keys.length - 1; + fields.keys.forEach((String key) { + TypeDefinition f = fields[key]; + String publicFieldName = fixFieldName(key, typeDef: f, privateField: false); _addTypeDef(f, sb); sb.write(' $publicFieldName'); @@ -262,11 +251,11 @@ class ClassDefinition { i++; }); sb.write('}) {\n'); - fields.keys.forEach((key) { - final f = fields[key]; - final publicFieldName = + fields.keys.forEach((String key) { + TypeDefinition f = fields[key]; + String publicFieldName = fixFieldName(key, typeDef: f, privateField: false); - final privateFieldName = + String privateFieldName = fixFieldName(key, typeDef: f, privateField: true); sb.write('this.$privateFieldName = $publicFieldName;\n'); }); @@ -275,13 +264,13 @@ class ClassDefinition { } String get _defaultConstructor { - final sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.write('\t$name({'); - var i = 0; - var len = fields.keys.length - 1; - fields.keys.forEach((key) { - final f = fields[key]; - final fieldName = + int i = 0; + int len = fields.keys.length - 1; + fields.keys.forEach((String key) { + TypeDefinition f = fields[key]; + String fieldName = fixFieldName(key, typeDef: f, privateField: privateFields); sb.write('this.$fieldName'); if (i != len) { @@ -294,10 +283,10 @@ class ClassDefinition { } String get _jsonParseFunc { - final sb = new StringBuffer(); + StringBuffer sb = new StringBuffer(); sb.write('\t$name'); sb.write('.fromJson(Map json) {\n'); - fields.keys.forEach((k) { + fields.keys.forEach((String k) { sb.write('\t\t${fields[k].jsonParseExpression(k, privateFields)}\n'); }); sb.write('\t}'); @@ -305,10 +294,10 @@ class ClassDefinition { } String get _jsonGenFunc { - final sb = new StringBuffer(); - sb.write( - '\tMap toJson() {\n\t\tfinal Map data = new Map();\n'); - fields.keys.forEach((k) { + StringBuffer sb = new StringBuffer(); + sb.write(''' +\tMap toJson() {\n\t\tfinal Map data = new Map();\n'''); + fields.keys.forEach((String k) { sb.write('\t\t${fields[k].toJsonExpression(k, privateFields)}\n'); }); sb.write('\t\treturn data;\n'); @@ -318,9 +307,11 @@ class ClassDefinition { String toString() { if (privateFields) { - return 'class $name {\n$_fieldList\n\n$_defaultPrivateConstructor\n\n$_gettersSetters\n\n$_jsonParseFunc\n\n$_jsonGenFunc\n}\n'; + return ''' +class $name {\n$_fieldList\n\n$_defaultPrivateConstructor\n\n$_gettersSetters\n\n$_jsonParseFunc\n\n$_jsonGenFunc\n}\n'''; } else { - return 'class $name {\n$_fieldList\n\n$_defaultConstructor\n\n$_jsonParseFunc\n\n$_jsonGenFunc\n}\n'; + return ''' +class $name {\n$_fieldList\n\n$_defaultConstructor\n\n$_jsonParseFunc\n\n$_jsonGenFunc\n}\n'''; } } } diff --git a/lib/warning.dart b/lib/warning.dart index 9324177..bbd5a20 100644 --- a/lib/warning.dart +++ b/lib/warning.dart @@ -1,13 +1,13 @@ class Warning { + Warning(this.warning, this.path); final String warning; final String path; - Warning(this.warning, this.path); } class WithWarning { + WithWarning(this.result, this.warnings); final T result; final List warnings; - WithWarning(this.result, this.warnings); } diff --git a/pubspec.yaml b/pubspec.yaml index a08239a..cd046d8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,11 +4,11 @@ author: Javier Lecuona description: A library that generates Dart classes (parse and generator included) from a json string. homepage: https://github.com/javiercbk/json_to_dart environment: - sdk: ">=2.0.0 <3.0.0" + sdk: ">=2.10.0 <3.0.0" dependencies: json_ast: "^1.0.5" - convert: "^2.0.1" - dart_style: "^1.0.10" + convert: ^3.0.0 + dart_style: ^2.0.0 dev_dependencies: test: "^1.9.4" diff --git a/test/array_root_test.dart b/test/array_root_test.dart index 3e5c1b4..15d4d77 100644 --- a/test/array_root_test.dart +++ b/test/array_root_test.dart @@ -1,29 +1,30 @@ import 'dart:io'; +import 'package:json_to_dart/model_generator.dart'; import 'package:path/path.dart' show dirname, join, normalize; import 'package:json_to_dart/json_to_dart.dart' show ModelGenerator; import 'package:test/test.dart'; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator", () { - final currentDirectory = dirname(_scriptPath()); + group('model-generator', () { + String currentDirectory = dirname(_scriptPath()); - test("Should generate the classes to parse the JSON", () { - final jsonPath = normalize(join(currentDirectory, 'array_root.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - final generator = ModelGenerator('ArrayRoot'); - final dartCode = generator.generateDartClasses(jsonRawData); + test('Should generate the classes to parse the JSON', () { + String jsonPath = normalize(join(currentDirectory, 'array_root.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + ModelGenerator generator = ModelGenerator('ArrayRoot'); + DartCode dartCode = generator.generateDartClasses(jsonRawData); expect(dartCode.warnings.length, equals(0)); expect(dartCode.code.contains('class GlossDiv'), equals(true)); }); diff --git a/test/bug_10_test.dart b/test/bug_10_test.dart index bebe0c1..d2b306b 100644 --- a/test/bug_10_test.dart +++ b/test/bug_10_test.dart @@ -1,97 +1,96 @@ import 'dart:io'; import 'dart:convert'; +import 'package:json_to_dart/model_generator.dart'; import 'package:path/path.dart' show dirname, join, normalize; import 'package:test/test.dart'; import 'package:json_to_dart/json_to_dart.dart' show ModelGenerator; import './generated/bug_ten.dart'; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator", () { - final currentDirectory = dirname(_scriptPath()); + group('model-generator', () { + String currentDirectory = dirname(_scriptPath()); - test("Should generate the classes to parse the JSON", () { - final jsonPath = normalize(join(currentDirectory, 'bug_10.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - final generator = ModelGenerator('BugTen'); - final dartCode = generator.generateDartClasses(jsonRawData); + test('Should generate the classes to parse the JSON', () { + String jsonPath = normalize(join(currentDirectory, 'bug_10.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + ModelGenerator generator = ModelGenerator('BugTen'); + DartCode dartCode = generator.generateDartClasses(jsonRawData); expect(dartCode.warnings.length, equals(0)); expect(dartCode.code.contains('class GlossDiv'), equals(true)); }); - test("Generated class should correctly parse JSON for bug 10", () { - final jsonPath = normalize(join(currentDirectory, 'bug_10.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - Map sampleMap = json.decode(jsonRawData); - final bugTen = new BugTen.fromJson(sampleMap); + test('Generated class should correctly parse JSON for bug 10', () { + String jsonPath = normalize(join(currentDirectory, 'bug_10.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + Map sampleMap = json.decode(jsonRawData); + BugTen bugTen = new BugTen.fromJson(sampleMap); expect(bugTen, isNot(isNull)); expect(bugTen.glossary, isNot(isNull)); expect(bugTen.glossary.title, equals('example glossary')); expect(bugTen.glossary.glossDiv, isNot(isNull)); - expect(bugTen.glossary.glossDiv.title, equals("S")); + expect(bugTen.glossary.glossDiv.title, equals('S')); expect(bugTen.glossary.glossDiv.glossList, isNot(isNull)); - final ge = bugTen.glossary.glossDiv.glossList.glossEntry; + GlossEntry ge = bugTen.glossary.glossDiv.glossList.glossEntry; expect(ge, isNot(isNull)); - expect(ge.iD, equals("SGML")); - expect(ge.sortAs, equals("SGML")); - expect(ge.glossTerm, equals("Standard Generalized Markup Language")); - expect(ge.acronym, equals("SGML")); - expect(ge.abbrev, equals("ISO 8879:1986")); - expect(ge.glossSee, equals("markup")); + expect(ge.iD, equals('SGML')); + expect(ge.sortAs, equals('SGML')); + expect(ge.glossTerm, equals('Standard Generalized Markup Language')); + expect(ge.acronym, equals('SGML')); + expect(ge.abbrev, equals('ISO 8879:1986')); + expect(ge.glossSee, equals('markup')); expect(ge.glossDef, isNot(isNull)); - expect( - ge.glossDef.para, - equals( - "A meta-markup language, used to create markup languages such as DocBook.")); - final seeAlso = ge.glossDef.glossSeeAlso; + expect(ge.glossDef.para, equals(''' +A meta-markup language, used to create markup languages such as DocBook.''')); + List seeAlso = ge.glossDef.glossSeeAlso; expect(seeAlso, isNot(isNull)); expect(seeAlso.length, equals(2)); - expect(seeAlso[0], equals("GML")); - expect(seeAlso[1], equals("XML")); + expect(seeAlso[0], equals('GML')); + expect(seeAlso[1], equals('XML')); }); - test("Generated class should correctly generate JSON", () { - final glossSeeAlso = new List(); - glossSeeAlso.add("GML"); - glossSeeAlso.add("XML"); - final glossDef = new GlossDef( - para: - "A meta-markup language, used to create markup languages such as DocBook.", + test('Generated class should correctly generate JSON', () { + List glossSeeAlso = []; + glossSeeAlso.add('GML'); + glossSeeAlso.add('XML'); + GlossDef glossDef = new GlossDef( + para: ''' +A meta-markup language, used to create markup languages such as DocBook.''', glossSeeAlso: glossSeeAlso); - final glossEntry = new GlossEntry( - abbrev: "ISO 8879:1986", - acronym: "SGML", + GlossEntry glossEntry = new GlossEntry( + abbrev: 'ISO 8879:1986', + acronym: 'SGML', glossDef: glossDef, - glossSee: "markup", - glossTerm: "Standard Generalized Markup Language", - iD: "SGML", - sortAs: "SGML", + glossSee: 'markup', + glossTerm: 'Standard Generalized Markup Language', + iD: 'SGML', + sortAs: 'SGML', ); - final glossList = new GlossList( + GlossList glossList = new GlossList( glossEntry: glossEntry, ); - final glossDiv = new GlossDiv( + GlossDiv glossDiv = new GlossDiv( glossList: glossList, - title: "S", + title: 'S', ); - final glossary = new Glossary( + Glossary glossary = new Glossary( glossDiv: glossDiv, - title: "example glossary", + title: 'example glossary', ); - final bugTen = new BugTen(glossary: glossary); - final codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); - final encodedJSON = codec.encode(bugTen.toJson()); + BugTen bugTen = new BugTen(glossary: glossary); + JsonCodec codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); + String encodedJSON = codec.encode(bugTen.toJson()); expect(encodedJSON.contains('"title":"example glossary"'), equals(true)); expect(encodedJSON.contains('"GlossDiv":{"title":"S"'), equals(true)); expect(encodedJSON.contains('"GlossList":{"GlossEntry":{'), equals(true)); @@ -103,9 +102,8 @@ void main() { equals(true)); expect(encodedJSON.contains('"Acronym":"SGML",'), equals(true)); expect(encodedJSON.contains('"Abbrev":"ISO 8879:1986",'), equals(true)); - expect( - encodedJSON.contains( - '"GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.",'), + expect(encodedJSON.contains(''' +"GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.",'''), equals(true)); expect( encodedJSON.contains('"GlossSeeAlso":["GML","XML"]'), equals(true)); diff --git a/test/bug_39_test.dart b/test/bug_39_test.dart index be33816..6bc891e 100644 --- a/test/bug_39_test.dart +++ b/test/bug_39_test.dart @@ -5,24 +5,24 @@ import 'package:test/test.dart'; import 'package:json_to_dart/json_to_dart.dart' show ModelGenerator; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator", () { - final currentDirectory = dirname(_scriptPath()); + group('model-generator', () { + String currentDirectory = dirname(_scriptPath()); - test("Should generate the classes to parse the JSON", () { - final jsonPath = normalize(join(currentDirectory, 'bug_39.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - final generator = ModelGenerator('BugThirtyNine'); + test('Should generate the classes to parse the JSON', () { + String jsonPath = normalize(join(currentDirectory, 'bug_39.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + ModelGenerator generator = ModelGenerator('BugThirtyNine'); // FIXME: Add matrix support // final dartCode = generator.generateDartClasses(jsonRawData); // expect(dartCode.warnings.length, equals(0)); diff --git a/test/bug_40_test.dart b/test/bug_40_test.dart index 63980fa..4c8b2b0 100644 --- a/test/bug_40_test.dart +++ b/test/bug_40_test.dart @@ -1,32 +1,33 @@ import 'dart:io'; +import 'package:json_to_dart/model_generator.dart'; import 'package:path/path.dart' show dirname, join, normalize; import 'package:test/test.dart'; import 'package:json_to_dart/json_to_dart.dart' show ModelGenerator; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator", () { - final currentDirectory = dirname(_scriptPath()); + group('model-generator', () { + String currentDirectory = dirname(_scriptPath()); - test("Should generate the classes to parse the JSON", () { - final jsonPath = normalize(join(currentDirectory, 'bug_40.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - final generator = ModelGenerator('BugForty'); - final dartCode = generator.generateDartClasses(jsonRawData); + test('Should generate the classes to parse the JSON', () { + String jsonPath = normalize(join(currentDirectory, 'bug_40.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + ModelGenerator generator = ModelGenerator('BugForty'); + DartCode dartCode = generator.generateDartClasses(jsonRawData); expect(dartCode.warnings.length, equals(1)); - expect(dartCode.warnings[0].warning, equals("list is empty")); - expect(dartCode.warnings[0].path, equals("/CustomButtons")); + expect(dartCode.warnings[0].warning, equals('list is empty')); + expect(dartCode.warnings[0].path, equals('/CustomButtons')); expect(dartCode.code.contains('class BugForty'), equals(true)); }); }); diff --git a/test/double_test.dart b/test/double_test.dart index 6f1cfa6..b5f6b4d 100644 --- a/test/double_test.dart +++ b/test/double_test.dart @@ -7,21 +7,21 @@ import 'package:json_to_dart/model_generator.dart'; import 'package:json_to_dart/helpers.dart' show isASTLiteralDouble; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("Should identify doubles and ints", () { - final currentDirectory = dirname(_scriptPath()); + group('Should identify doubles and ints', () { + String currentDirectory = dirname(_scriptPath()); - test("should parse literals correctly", () { + test('should parse literals correctly', () { expect(isASTLiteralDouble(LiteralNode(1, '1')), isFalse); expect(isASTLiteralDouble(LiteralNode(1e0, '1e0')), isFalse); expect(isASTLiteralDouble(LiteralNode(1e1, '1e1')), isFalse); @@ -45,16 +45,18 @@ void main() { expect(isASTLiteralDouble(LiteralNode(0.1, '0.1')), isTrue); }); - test("Should identify a double number and generate the proper type", () { - final jsonPath = normalize(join(currentDirectory, 'double.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - final modelGenerator = ModelGenerator('DoubleTest'); - final dartSourceCode = modelGenerator.generateDartClasses(jsonRawData); - final wrongDoubleRegExp = RegExp(r"^.*double int[0-9]+;$"); - final wrongIntRegExp = RegExp(r"^.*int double[0-9]+;$"); - final wrongDoubleMatch = + test('Should identify a double number and generate the proper type', () { + String jsonPath = normalize(join(currentDirectory, 'double.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + ModelGenerator modelGenerator = ModelGenerator('DoubleTest'); + DartCode dartSourceCode = + modelGenerator.generateDartClasses(jsonRawData); + RegExp wrongDoubleRegExp = RegExp(r'^.*double int[0-9]+;$'); + RegExp wrongIntRegExp = RegExp(r'^.*int double[0-9]+;$'); + RegExpMatch wrongDoubleMatch = wrongDoubleRegExp.firstMatch(dartSourceCode.code); - final wrongIntMatch = wrongIntRegExp.firstMatch(dartSourceCode.code); + RegExpMatch wrongIntMatch = + wrongIntRegExp.firstMatch(dartSourceCode.code); expect(wrongDoubleMatch, isNull, reason: 'Wrong double found'); expect(wrongIntMatch, isNull, reason: 'Wrong int found'); }); diff --git a/test/generated/bug_ten.dart b/test/generated/bug_ten.dart index 036992c..d08fd08 100644 --- a/test/generated/bug_ten.dart +++ b/test/generated/bug_ten.dart @@ -1,5 +1,4 @@ class BugTen { - Glossary glossary; BugTen({this.glossary}); @@ -8,9 +7,10 @@ class BugTen { ? new Glossary.fromJson(json['glossary']) : null; } + Glossary glossary; Map toJson() { - final Map data = new Map(); + Map data = new Map(); if (this.glossary != null) { data['glossary'] = this.glossary.toJson(); } @@ -19,8 +19,6 @@ class BugTen { } class Glossary { - String title; - GlossDiv glossDiv; Glossary({this.title, this.glossDiv}); @@ -30,9 +28,11 @@ class Glossary { ? new GlossDiv.fromJson(json['GlossDiv']) : null; } + String title; + GlossDiv glossDiv; Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['title'] = this.title; if (this.glossDiv != null) { data['GlossDiv'] = this.glossDiv.toJson(); @@ -42,8 +42,6 @@ class Glossary { } class GlossDiv { - String title; - GlossList glossList; GlossDiv({this.title, this.glossList}); @@ -53,9 +51,11 @@ class GlossDiv { ? new GlossList.fromJson(json['GlossList']) : null; } + String title; + GlossList glossList; Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['title'] = this.title; if (this.glossList != null) { data['GlossList'] = this.glossList.toJson(); @@ -65,7 +65,6 @@ class GlossDiv { } class GlossList { - GlossEntry glossEntry; GlossList({this.glossEntry}); @@ -74,9 +73,10 @@ class GlossList { ? new GlossEntry.fromJson(json['GlossEntry']) : null; } + GlossEntry glossEntry; Map toJson() { - final Map data = new Map(); + Map data = new Map(); if (this.glossEntry != null) { data['GlossEntry'] = this.glossEntry.toJson(); } @@ -85,14 +85,6 @@ class GlossList { } class GlossEntry { - String iD; - String sortAs; - String glossTerm; - String acronym; - String abbrev; - GlossDef glossDef; - String glossSee; - GlossEntry( {this.iD, this.sortAs, @@ -113,9 +105,16 @@ class GlossEntry { : null; glossSee = json['GlossSee']; } + String iD; + String sortAs; + String glossTerm; + String acronym; + String abbrev; + GlossDef glossDef; + String glossSee; Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['ID'] = this.iD; data['SortAs'] = this.sortAs; data['GlossTerm'] = this.glossTerm; @@ -130,18 +129,17 @@ class GlossEntry { } class GlossDef { - String para; - List glossSeeAlso; - GlossDef({this.para, this.glossSeeAlso}); GlossDef.fromJson(Map json) { para = json['para']; glossSeeAlso = json['GlossSeeAlso'].cast(); } + String para; + List glossSeeAlso; Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['para'] = this.para; data['GlossSeeAlso'] = this.glossSeeAlso; return data; diff --git a/test/generated/sample.dart b/test/generated/sample.dart index a166b21..3fc2efd 100644 --- a/test/generated/sample.dart +++ b/test/generated/sample.dart @@ -1,14 +1,4 @@ class Sample { - String username; - int favouriteInteger; - double favouriteDouble; - String url; - String htmlUrl; - List tags; - List randomIntegers; - List randomDoubles; - PersonalInfo personalInfo; - Sample( {this.username, this.favouriteInteger, @@ -34,8 +24,17 @@ class Sample { : null; } + String username; + int favouriteInteger; + double favouriteDouble; + String url; + String htmlUrl; + List tags; + List randomIntegers; + List randomDoubles; + PersonalInfo personalInfo; Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['username'] = this.username; data['favouriteInteger'] = this.favouriteInteger; data['favouriteDouble'] = this.favouriteDouble; @@ -52,11 +51,6 @@ class Sample { } class PersonalInfo { - String firstName; - String lastName; - String location; - List phones; - PersonalInfo({this.firstName, this.lastName, this.location, this.phones}); PersonalInfo.fromJson(Map json) { @@ -64,30 +58,30 @@ class PersonalInfo { lastName = json['lastName']; location = json['location']; if (json['phones'] != null) { - phones = new List(); - json['phones'].forEach((v) { + phones = []; + json['phones'].forEach((dynamic v) { phones.add(new Phones.fromJson(v)); }); } } + String firstName; + String lastName; + String location; + List phones; Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['firstName'] = this.firstName; data['lastName'] = this.lastName; data['location'] = this.location; if (this.phones != null) { - data['phones'] = this.phones.map((v) => v.toJson()).toList(); + data['phones'] = this.phones.map((Phones v) => v.toJson()).toList(); } return data; } } class Phones { - String type; - String number; - bool shouldCall; - Phones({this.type, this.number, this.shouldCall}); Phones.fromJson(Map json) { @@ -95,9 +89,12 @@ class Phones { number = json['number']; shouldCall = json['shouldCall']; } + String type; + String number; + bool shouldCall; Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['type'] = this.type; data['number'] = this.number; data['shouldCall'] = this.shouldCall; diff --git a/test/generated/sample_private.dart b/test/generated/sample_private.dart index 5665918..84994f6 100644 --- a/test/generated/sample_private.dart +++ b/test/generated/sample_private.dart @@ -1,13 +1,4 @@ class Sample { - String _username; - int _favouriteInteger; - double _favouriteDouble; - String _url; - String _htmlUrl; - List _tags; - List _randomIntegers; - List _randomDoubles; - PersonalInfo _personalInfo; Sample( {String username, @@ -29,7 +20,28 @@ class Sample { this._randomDoubles = randomDoubles; this._personalInfo = personalInfo; } - +Sample.fromJson(Map json) { + _username = json['username']; + _favouriteInteger = json['favouriteInteger']; + _favouriteDouble = json['favouriteDouble']; + _url = json['url']; + _htmlUrl = json['html_url']; + _tags = json['tags'].cast(); + _randomIntegers = json['randomIntegers'].cast(); + _randomDoubles = json['randomDoubles'].cast(); + _personalInfo = json['personalInfo'] != null + ? new PersonalInfo.fromJson(json['personalInfo']) + : null; + } + String _username; + int _favouriteInteger; + double _favouriteDouble; + String _url; + String _htmlUrl; + List _tags; + List _randomIntegers; + List _randomDoubles; + PersonalInfo _personalInfo; String get username => _username; set username(String username) => _username = username; int get favouriteInteger => _favouriteInteger; @@ -53,22 +65,10 @@ class Sample { PersonalInfo get personalInfo => _personalInfo; set personalInfo(PersonalInfo personalInfo) => _personalInfo = personalInfo; - Sample.fromJson(Map json) { - _username = json['username']; - _favouriteInteger = json['favouriteInteger']; - _favouriteDouble = json['favouriteDouble']; - _url = json['url']; - _htmlUrl = json['html_url']; - _tags = json['tags'].cast(); - _randomIntegers = json['randomIntegers'].cast(); - _randomDoubles = json['randomDoubles'].cast(); - _personalInfo = json['personalInfo'] != null - ? new PersonalInfo.fromJson(json['personalInfo']) - : null; - } + Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['username'] = this._username; data['favouriteInteger'] = this._favouriteInteger; data['favouriteDouble'] = this._favouriteDouble; @@ -85,10 +85,6 @@ class Sample { } class PersonalInfo { - String _firstName; - String _lastName; - String _location; - List _phones; PersonalInfo( {String firstName, @@ -100,7 +96,22 @@ class PersonalInfo { this._location = location; this._phones = phones; } +PersonalInfo.fromJson(Map json) { + _firstName = json['firstName']; + _lastName = json['lastName']; + _location = json['location']; + if (json['phones'] != null) { + _phones = []; + json['phones'].forEach((Map v) { + _phones.add(new Phones.fromJson(v)); + }); + } + } + String _firstName; + String _lastName; + String _location; + List _phones; String get firstName => _firstName; set firstName(String firstName) => _firstName = firstName; String get lastName => _lastName; @@ -110,40 +121,34 @@ class PersonalInfo { List get phones => _phones; set phones(List phones) => _phones = phones; - PersonalInfo.fromJson(Map json) { - _firstName = json['firstName']; - _lastName = json['lastName']; - _location = json['location']; - if (json['phones'] != null) { - _phones = new List(); - json['phones'].forEach((v) { - _phones.add(new Phones.fromJson(v)); - }); - } - } - + Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['firstName'] = this._firstName; data['lastName'] = this._lastName; data['location'] = this._location; if (this._phones != null) { - data['phones'] = this._phones.map((v) => v.toJson()).toList(); + data['phones'] = this._phones.map((Phones v) => v.toJson()).toList(); } return data; } } class Phones { - String _type; - String _number; - bool _shouldCall; Phones({String type, String number, bool shouldCall}) { this._type = type; this._number = number; this._shouldCall = shouldCall; } + Phones.fromJson(Map json) { + _type = json['type']; + _number = json['number']; + _shouldCall = json['shouldCall']; + } + String _type; + String _number; + bool _shouldCall; String get type => _type; set type(String type) => _type = type; @@ -152,14 +157,9 @@ class Phones { bool get shouldCall => _shouldCall; set shouldCall(bool shouldCall) => _shouldCall = shouldCall; - Phones.fromJson(Map json) { - _type = json['type']; - _number = json['number']; - _shouldCall = json['shouldCall']; - } Map toJson() { - final Map data = new Map(); + Map data = new Map(); data['type'] = this._type; data['number'] = this._number; data['shouldCall'] = this._shouldCall; diff --git a/test/helpers_test.dart b/test/helpers_test.dart index b2fd428..ccfc936 100644 --- a/test/helpers_test.dart +++ b/test/helpers_test.dart @@ -3,31 +3,31 @@ import 'package:json_to_dart/helpers.dart'; import 'package:json_to_dart/syntax.dart'; void main() { - group("helpers", () { - test("camelCase should correctly transform Strings", () { - const Map mappings = const { + group('helpers', () { + test('camelCase should correctly transform Strings', () { + const Map mappings = { 'kebab-case': 'KebabCase', 'snake_case': 'SnakeCase', 'CamelCase': 'CamelCase', 'camelCase': 'CamelCase', }; - mappings.keys.forEach((key) { + mappings.keys.forEach((String key) { expect(camelCase(key), equals(mappings[key])); }); }); - test("camelCaseFirstLower should correctly transform Strings", () { - const Map mappings = const { + test('camelCaseFirstLower should correctly transform Strings', () { + const Map mappings = { 'kebab-case': 'kebabCase', 'snake_case': 'snakeCase', 'CamelCase': 'camelCase', 'camelCase': 'camelCase', }; - mappings.keys.forEach((key) { + mappings.keys.forEach((String key) { expect(camelCaseFirstLower(key), equals(mappings[key])); }); }); - test("fixFieldName should avoid offending variable names", () { + test('fixFieldName should avoid offending variable names', () { expect( fixFieldName('48x48', typeDef: new TypeDefinition( diff --git a/test/matrix_test.dart b/test/matrix_test.dart index d422368..c5d8856 100644 --- a/test/matrix_test.dart +++ b/test/matrix_test.dart @@ -5,24 +5,24 @@ import 'package:test/test.dart'; import 'package:json_to_dart/json_to_dart.dart' show ModelGenerator; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator", () { - final currentDirectory = dirname(_scriptPath()); + group('model-generator', () { + String currentDirectory = dirname(_scriptPath()); - test("Should generate the classes to parse the JSON", () { - final jsonPath = normalize(join(currentDirectory, 'matrix.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - final generator = ModelGenerator('Matrix'); + test('Should generate the classes to parse the JSON', () { + String jsonPath = normalize(join(currentDirectory, 'matrix.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + ModelGenerator generator = ModelGenerator('Matrix'); // FIXME: Add matrix support // final dartCode = generator.generateDartClasses(jsonRawData); // expect(dartCode.warnings.length, equals(1)); diff --git a/test/model_generator_private_test.dart b/test/model_generator_private_test.dart index c37d19a..542b51d 100644 --- a/test/model_generator_private_test.dart +++ b/test/model_generator_private_test.dart @@ -5,24 +5,24 @@ import 'package:test/test.dart'; import './generated/sample_private.dart'; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator", () { - final currentDirectory = dirname(_scriptPath()); - test("Generated class with private fields should correctly parse JSON", () { - final jsonPath = normalize(join(currentDirectory, 'test.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - Map sampleMap = json.decode(jsonRawData); - final sample = new Sample.fromJson(sampleMap); + group('model-generator', () { + String currentDirectory = dirname(_scriptPath()); + test('Generated class with private fields should correctly parse JSON', () { + String jsonPath = normalize(join(currentDirectory, 'test.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + Map sampleMap = json.decode(jsonRawData); + Sample sample = new Sample.fromJson(sampleMap); expect(sample, isNot(isNull)); expect(sample.username, equals('javiercbk')); expect(sample.favouriteInteger, equals(18)); @@ -44,12 +44,12 @@ void main() { expect(sample.randomDoubles[0], equals(1.1)); expect(sample.randomDoubles[1], equals(2.2)); expect(sample.randomDoubles[2], equals(3.3)); - final pi = sample.personalInfo; + PersonalInfo pi = sample.personalInfo; expect(pi, isNot(isNull)); expect(pi.firstName, equals('Javier')); expect(pi.lastName, equals('Lecuona')); expect(pi.location, equals('Buenos Aires, Argentina')); - final ph = pi.phones; + List ph = pi.phones; expect(ph, isNot(isNull)); expect(ph.length, equals(2)); expect(ph[0], isNot(isNull)); @@ -62,13 +62,13 @@ void main() { expect(ph[1].shouldCall, equals(false)); }); - test( - "Generated class with private fields should correctly parse JSON with missing values", + test(''' +Generated class with private fields should correctly parse JSON with missing values''', () { - final jsonPath = normalize(join(currentDirectory, 'test_missing.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - Map sampleMap = json.decode(jsonRawData); - final sample = new Sample.fromJson(sampleMap); + String jsonPath = normalize(join(currentDirectory, 'test_missing.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + Map sampleMap = json.decode(jsonRawData); + Sample sample = new Sample.fromJson(sampleMap); expect(sample, isNot(isNull)); expect(sample.username, equals('javiercbk')); expect(sample.favouriteInteger, isNull); @@ -90,7 +90,7 @@ void main() { expect(sample.randomDoubles[0], equals(1.1)); expect(sample.randomDoubles[1], equals(2.2)); expect(sample.randomDoubles[2], equals(3.3)); - final pi = sample.personalInfo; + PersonalInfo pi = sample.personalInfo; expect(pi, isNot(isNull)); expect(pi.firstName, equals('Javier')); expect(pi.lastName, isNull); @@ -98,34 +98,34 @@ void main() { expect(pi.phones, isNull); }); - test("Generated class with private fields should correctly generate JSON", + test('Generated class with private fields should correctly generate JSON', () { - final phones = new List(); - final phone = new Phones( - type: "IP", - number: "127.0.0.1", + List phones = []; + Phones phone = new Phones( + type: 'IP', + number: '127.0.0.1', shouldCall: true, ); phones.add(phone); - final personalInfo = new PersonalInfo( - firstName: "User", - lastName: "Test", - location: "In a computer", + PersonalInfo personalInfo = new PersonalInfo( + firstName: 'User', + lastName: 'Test', + location: 'In a computer', phones: phones, ); - final sample = new Sample( + Sample sample = new Sample( username: 'Test', favouriteInteger: 13, favouriteDouble: 3.1416, url: 'http://test.test', htmlUrl: 'http://anothertest.test', - tags: const ['test1'], - randomIntegers: const [4, 5], - randomDoubles: const [4.4, 5.5], + tags: ['test1'], + randomIntegers: [4, 5], + randomDoubles: [4.4, 5.5], personalInfo: personalInfo, ); - final codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); - final encodedJSON = codec.encode(sample.toJson()); + JsonCodec codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); + String encodedJSON = codec.encode(sample.toJson()); expect(encodedJSON.contains('"username":"Test"'), equals(true)); expect(encodedJSON.contains('"favouriteInteger":13'), equals(true)); expect(encodedJSON.contains('"favouriteDouble":3.1416'), equals(true)); @@ -145,25 +145,25 @@ void main() { expect(encodedJSON.contains('"shouldCall":true'), equals(true)); }); - test( - "Generated class with private fields should correctly generate JSON with missing values", + test(''' +Generated class with private fields should correctly generate JSON with missing values''', () { - final personalInfo = new PersonalInfo( - firstName: "User", + PersonalInfo personalInfo = new PersonalInfo( + firstName: 'User', lastName: null, ); - final sample = new Sample( + Sample sample = new Sample( username: 'Test', favouriteInteger: null, favouriteDouble: 3.1416, url: 'http://test.test', - tags: const ['test1'], - randomIntegers: const [4, 5], - randomDoubles: const [4.4, 5.5], + tags: ['test1'], + randomIntegers: [4, 5], + randomDoubles: [4.4, 5.5], personalInfo: personalInfo, ); - final codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); - final encodedJSON = codec.encode(sample.toJson()); + JsonCodec codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); + String encodedJSON = codec.encode(sample.toJson()); expect(encodedJSON.contains('"username":"Test"'), equals(true)); expect(encodedJSON.contains('"favouriteInteger":null'), equals(true)); expect(encodedJSON.contains('"favouriteDouble":3.1416'), equals(true)); diff --git a/test/model_generator_test.dart b/test/model_generator_test.dart index e3e16a5..840e60f 100644 --- a/test/model_generator_test.dart +++ b/test/model_generator_test.dart @@ -5,24 +5,24 @@ import 'package:test/test.dart'; import './generated/sample.dart'; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator", () { - final currentDirectory = dirname(_scriptPath()); - test("Generated class should correctly parse JSON", () { - final jsonPath = normalize(join(currentDirectory, 'test.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - Map sampleMap = json.decode(jsonRawData); - final sample = new Sample.fromJson(sampleMap); + group('model-generator', () { + String currentDirectory = dirname(_scriptPath()); + test('Generated class should correctly parse JSON', () { + String jsonPath = normalize(join(currentDirectory, 'test.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + Map sampleMap = json.decode(jsonRawData); + Sample sample = new Sample.fromJson(sampleMap); expect(sample, isNot(isNull)); expect(sample.username, equals('javiercbk')); expect(sample.favouriteInteger, equals(18)); @@ -44,12 +44,12 @@ void main() { expect(sample.randomDoubles[0], equals(1.1)); expect(sample.randomDoubles[1], equals(2.2)); expect(sample.randomDoubles[2], equals(3.3)); - final pi = sample.personalInfo; + PersonalInfo pi = sample.personalInfo; expect(pi, isNot(isNull)); expect(pi.firstName, equals('Javier')); expect(pi.lastName, equals('Lecuona')); expect(pi.location, equals('Buenos Aires, Argentina')); - final ph = pi.phones; + List ph = pi.phones; expect(ph, isNot(isNull)); expect(ph.length, equals(2)); expect(ph[0], isNot(isNull)); @@ -62,11 +62,11 @@ void main() { expect(ph[1].shouldCall, equals(false)); }); - test("Generated class should correctly parse JSON with missing values", () { - final jsonPath = normalize(join(currentDirectory, 'test_missing.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - Map sampleMap = json.decode(jsonRawData); - final sample = new Sample.fromJson(sampleMap); + test('Generated class should correctly parse JSON with missing values', () { + String jsonPath = normalize(join(currentDirectory, 'test_missing.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + Map sampleMap = json.decode(jsonRawData); + Sample sample = new Sample.fromJson(sampleMap); expect(sample, isNot(isNull)); expect(sample.username, equals('javiercbk')); expect(sample.favouriteInteger, isNull); @@ -88,7 +88,7 @@ void main() { expect(sample.randomDoubles[0], equals(1.1)); expect(sample.randomDoubles[1], equals(2.2)); expect(sample.randomDoubles[2], equals(3.3)); - final pi = sample.personalInfo; + PersonalInfo pi = sample.personalInfo; expect(pi, isNot(isNull)); expect(pi.firstName, equals('Javier')); expect(pi.lastName, isNull); @@ -96,33 +96,33 @@ void main() { expect(pi.phones, isNull); }); - test("Generated class should correctly generate JSON", () { - final phones = new List(); - final phone = new Phones( - type: "IP", - number: "127.0.0.1", + test('Generated class should correctly generate JSON', () { + List phones = []; + Phones phone = Phones( + type: 'IP', + number: '127.0.0.1', shouldCall: true, ); phones.add(phone); - final personalInfo = new PersonalInfo( - firstName: "User", - lastName: "Test", - location: "In a computer", + PersonalInfo personalInfo = new PersonalInfo( + firstName: 'User', + lastName: 'Test', + location: 'In a computer', phones: phones, ); - final sample = new Sample( + Sample sample = new Sample( username: 'Test', favouriteInteger: 13, favouriteDouble: 3.1416, url: 'http://test.test', htmlUrl: 'http://anothertest.test', - tags: const ['test1'], - randomIntegers: const [4, 5], - randomDoubles: const [4.4, 5.5], + tags: ['test1'], + randomIntegers: [4, 5], + randomDoubles: [4.4, 5.5], personalInfo: personalInfo, ); - final codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); - final encodedJSON = codec.encode(sample.toJson()); + JsonCodec codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); + String encodedJSON = codec.encode(sample.toJson()); expect(encodedJSON.contains('"username":"Test"'), equals(true)); expect(encodedJSON.contains('"favouriteInteger":13'), equals(true)); expect(encodedJSON.contains('"favouriteDouble":3.1416'), equals(true)); @@ -142,24 +142,24 @@ void main() { expect(encodedJSON.contains('"shouldCall":true'), equals(true)); }); - test("Generated class should correctly generate JSON with missing values", + test('Generated class should correctly generate JSON with missing values', () { - final personalInfo = new PersonalInfo( - firstName: "User", + PersonalInfo personalInfo = new PersonalInfo( + firstName: 'User', lastName: null, ); - final sample = new Sample( + Sample sample = new Sample( username: 'Test', favouriteInteger: null, favouriteDouble: 3.1416, url: 'http://test.test', - tags: const ['test1'], - randomIntegers: const [4, 5], - randomDoubles: const [4.4, 5.5], + tags: ['test1'], + randomIntegers: [4, 5], + randomDoubles: [4.4, 5.5], personalInfo: personalInfo, ); - final codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); - final encodedJSON = codec.encode(sample.toJson()); + JsonCodec codec = new JsonCodec(toEncodable: (dynamic v) => v.toString()); + String encodedJSON = codec.encode(sample.toJson()); expect(encodedJSON.contains('"username":"Test"'), equals(true)); expect(encodedJSON.contains('"favouriteInteger":null'), equals(true)); expect(encodedJSON.contains('"favouriteDouble":3.1416'), equals(true)); diff --git a/test/model_generator_warnings_test.dart b/test/model_generator_warnings_test.dart index 5750ccb..7a7ef09 100644 --- a/test/model_generator_warnings_test.dart +++ b/test/model_generator_warnings_test.dart @@ -4,34 +4,34 @@ import 'package:path/path.dart' show dirname, join, normalize; import 'package:test/test.dart'; String _scriptPath() { - var script = Platform.script.toString(); - if (script.startsWith("file://")) { + String script = Platform.script.toString(); + if (script.startsWith('file://')) { script = script.substring(7); } else { - final idx = script.indexOf("file:/"); + int idx = script.indexOf('file:/'); script = script.substring(idx + 5); } return script; } void main() { - group("model-generator-with-warnings", () { - final currentDirectory = dirname(_scriptPath()); - test("should generate proper warnings", () { - final jsonPath = normalize(join(currentDirectory, 'test_warnings.json')); - final jsonRawData = new File(jsonPath).readAsStringSync(); - final ModelGenerator modelGenerator = new ModelGenerator("Warnings"); + group('model-generator-with-warnings', () { + String currentDirectory = dirname(_scriptPath()); + test('should generate proper warnings', () { + String jsonPath = normalize(join(currentDirectory, 'test_warnings.json')); + String jsonRawData = new File(jsonPath).readAsStringSync(); + ModelGenerator modelGenerator = new ModelGenerator('Warnings'); DartCode dartCode = modelGenerator.generateUnsafeDart(jsonRawData); expect(dartCode.warnings, isNot(null)); expect(dartCode.warnings.length, equals(4)); - expect(dartCode.warnings[0].warning, equals("list is ambiguous")); - expect(dartCode.warnings[0].path, equals("/ambiguousArray")); - expect(dartCode.warnings[1].warning, equals("list is empty")); - expect(dartCode.warnings[1].path, equals("/emptyArr")); - expect(dartCode.warnings[2].warning, equals("type is ambiguous")); - expect(dartCode.warnings[2].path, equals("/ambiguous[2]/arr[0]/amb")); - expect(dartCode.warnings[3].warning, equals("list is empty")); - expect(dartCode.warnings[3].path, equals("/ambiguous/arr/emptyArr")); + expect(dartCode.warnings[0].warning, equals('list is ambiguous')); + expect(dartCode.warnings[0].path, equals('/ambiguousArray')); + expect(dartCode.warnings[1].warning, equals('list is empty')); + expect(dartCode.warnings[1].path, equals('/emptyArr')); + expect(dartCode.warnings[2].warning, equals('type is ambiguous')); + expect(dartCode.warnings[2].path, equals('/ambiguous[2]/arr[0]/amb')); + expect(dartCode.warnings[3].warning, equals('list is empty')); + expect(dartCode.warnings[3].path, equals('/ambiguous/arr/emptyArr')); }); }); }