| // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file | |
| // for details. 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'; | |
| import 'dart:io'; | |
| import 'dart:isolate'; | |
| import 'package:html/dom.dart' show Element; | |
| import 'package:html/parser.dart' show parseFragment; | |
| import 'package:markdown/markdown.dart' | |
| show | |
| AutolinkExtensionSyntax, | |
| BlockSyntax, | |
| InlineSyntax, | |
| StrikethroughSyntax, | |
| TableSyntax, | |
| markdownToHtml; | |
| import 'package:path/path.dart' as p; | |
| import '../test/util.dart'; | |
| // Locate the "tool" directory. Use `Isolate.resolvePackageUriSync` so that this | |
| // works with the test package, which loads this suite into an isolate. | |
| final String toolDir = p.fromUri( | |
| Isolate.resolvePackageUriSync( | |
| Uri.parse('package:markdown/'), | |
| )!.resolve('../tool'), | |
| ); | |
| File getStatsFile(String prefix) => | |
| File(p.join(toolDir, '${prefix}_stats.json')); | |
| File getTestsFile(String prefix) => | |
| File(p.join(toolDir, '${prefix}_tests.json')); | |
| File get divergencesFile => File(p.join(toolDir, 'divergences.json')); | |
| /// An intentional, documented difference between this package's output and | |
| /// the spec's expected output for a single example. | |
| /// | |
| /// The example is scored [CompareLevel.diverged] only while the actual output | |
| /// equals [html]; any other output is scored as usual. | |
| class Divergence { | |
| final String reason; | |
| final String link; | |
| final String html; | |
| Divergence({required this.reason, required this.link, required this.html}); | |
| factory Divergence.fromJson(Map<String, dynamic> json) => Divergence( | |
| reason: json['reason'] as String, | |
| link: json['link'] as String, | |
| html: json['html'] as String, | |
| ); | |
| } | |
| /// Loads the [Divergence]s for [prefix], keyed by spec example number. | |
| Map<int, Divergence> loadDivergences(String prefix) { | |
| final json = | |
| jsonDecode(divergencesFile.readAsStringSync()) as Map<String, dynamic>; | |
| final entries = json[prefix] as Map<String, dynamic>? ?? const {}; | |
| return { | |
| for (final MapEntry(:key, :value) in entries.entries) | |
| int.parse(key): Divergence.fromJson(value as Map<String, dynamic>), | |
| }; | |
| } | |
| final _exampleStartFence = RegExp(r'^`{32} example(.*)$'); | |
| final _exampleEndFence = RegExp(r'^`{32}$'); | |
| final _headerPrefix = RegExp('^#+ '); | |
| final _htmlComment = RegExp('<!--.*?-->', dotAll: true); | |
| /// Parses CommonMark / GFM spec test cases from raw `spec.txt` contents. | |
| List<CommonMarkTestCase> parseSpecExamples(String specMarkdown) { | |
| final tests = <CommonMarkTestCase>[]; | |
| final lines = const LineSplitter().convert(specMarkdown); | |
| var example = 0; | |
| var section = ''; | |
| for (var i = 0; i < lines.length; i++) { | |
| final line = lines[i]; | |
| final extensions = _tryParseExampleFence(line); | |
| if (extensions != null) { | |
| example++; | |
| final startLine = i + 1; | |
| final (dotIndex, endIndex) = _findExampleBounds(lines, i); | |
| if (!extensions.contains('disabled')) { | |
| tests.add( | |
| CommonMarkTestCase( | |
| example, | |
| section, | |
| startLine, | |
| endIndex + 1, | |
| _joinSpecLines(lines.sublist(i + 1, dotIndex)), | |
| _joinSpecLines(lines.sublist(dotIndex + 1, endIndex)), | |
| extensions, | |
| ), | |
| ); | |
| } | |
| i = endIndex; | |
| } else if (_headerPrefix.hasMatch(line)) { | |
| section = _parseSectionHeader(line); | |
| } | |
| } | |
| return tests; | |
| } | |
| (int, int) _findExampleBounds(List<String> lines, int startIndex) { | |
| final dotIndex = lines.indexOf('.', startIndex + 1); | |
| if (dotIndex == -1) { | |
| throw FormatException( | |
| 'Malformed spec: missing "." separator for example at line ' | |
| '${startIndex + 1}.', | |
| ); | |
| } | |
| final endIndex = lines.indexWhere(_exampleEndFence.hasMatch, dotIndex + 1); | |
| if (endIndex == -1) { | |
| throw FormatException( | |
| 'Malformed spec: missing closing fence for example at line ' | |
| '${startIndex + 1}.', | |
| ); | |
| } | |
| return (dotIndex, endIndex); | |
| } | |
| String _joinSpecLines(List<String> lines) => | |
| lines.map((l) => '${l.replaceAll('→', '\t')}\n').join(); | |
| Set<String>? _tryParseExampleFence(String line) { | |
| final match = _exampleStartFence.firstMatch(line); | |
| if (match == null) return null; | |
| final extText = match.group(1)!.trim(); | |
| return extText.isEmpty ? const {} : extText.split(RegExp(r'\s+')).toSet(); | |
| } | |
| String _parseSectionHeader(String line) => | |
| line.replaceFirst(_headerPrefix, '').replaceAll(_htmlComment, '').trim(); | |
| Map<String, List<CommonMarkTestCase>> loadCommonMarkSections( | |
| String testPrefix, | |
| ) { | |
| final testFile = getTestsFile(testPrefix); | |
| final testsJson = testFile.readAsStringSync(); | |
| final testArray = jsonDecode(testsJson) as List; | |
| final sections = <String, List<CommonMarkTestCase>>{}; | |
| for (final exampleMap in testArray) { | |
| final exampleTest = CommonMarkTestCase.fromJson( | |
| exampleMap as Map<String, dynamic>, | |
| ); | |
| final sectionList = sections.putIfAbsent( | |
| exampleTest.section, | |
| () => <CommonMarkTestCase>[], | |
| ); | |
| sectionList.add(exampleTest); | |
| } | |
| return sections; | |
| } | |
| class Config { | |
| static final Config commonMarkConfig = Config._( | |
| 'common_mark', | |
| 'https://spec.commonmark.org/0.31.2/', | |
| 'commonmark/commonmark-spec', | |
| 'spec.txt', | |
| ); | |
| static final Config gfmConfig = Config._( | |
| 'gfm', | |
| 'https://github.github.com/gfm/', | |
| 'github/cmark-gfm', | |
| 'test/spec.txt', | |
| ); | |
| final String prefix; | |
| final String baseUrl; | |
| final String githubRepo; | |
| final String specFilePath; | |
| late final Map<int, Divergence> divergences = loadDivergences(prefix); | |
| Config._(this.prefix, this.baseUrl, this.githubRepo, this.specFilePath); | |
| } | |
| class CommonMarkTestCase { | |
| final String markdown; | |
| final String section; | |
| final int example; | |
| final String html; | |
| final int startLine; | |
| final int endLine; | |
| final Set<String> extensions; | |
| CommonMarkTestCase( | |
| this.example, | |
| this.section, | |
| this.startLine, | |
| this.endLine, | |
| this.markdown, | |
| this.html, | |
| this.extensions, | |
| ); | |
| factory CommonMarkTestCase.fromJson(Map<String, dynamic> json) { | |
| return CommonMarkTestCase( | |
| json['example'] as int, | |
| json['section'] as String /*!*/, | |
| json['start_line'] as int, | |
| json['end_line'] as int, | |
| json['markdown'] as String /*!*/, | |
| json['html'] as String, | |
| json['extensions'] == null | |
| ? const {} | |
| : Set.from(json['extensions'] as List), | |
| ); | |
| } | |
| Map<String, Object?> toJson() => { | |
| 'markdown': markdown, | |
| 'html': html, | |
| 'example': example, | |
| 'start_line': startLine, | |
| 'end_line': endLine, | |
| 'section': section, | |
| if (extensions.isNotEmpty) 'extensions': extensions.toList(), | |
| }; | |
| @override | |
| String toString() => '$section - $example'; | |
| } | |
| enum CompareLevel { | |
| strict, | |
| loose, | |
| /// Output intentionally differs from the spec; see `tool/divergences.json`. | |
| /// | |
| /// Counted as neither passing nor failing. | |
| diverged, | |
| fail, | |
| error, | |
| } | |
| class CompareResult { | |
| final CompareLevel compareLevel; | |
| final CommonMarkTestCase testCase; | |
| final String? result; | |
| CompareResult(this.testCase, this.result, this.compareLevel); | |
| } | |
| CompareResult compareResult( | |
| Config config, | |
| CommonMarkTestCase testCase, { | |
| bool throwOnError = false, | |
| bool verboseFail = false, | |
| bool verboseLooseMatch = false, | |
| Set<String> extensions = const {}, | |
| }) { | |
| var enabletagfilter = false; | |
| String output; | |
| final inlineSyntaxes = <InlineSyntax>[]; | |
| final blockSyntaxes = <BlockSyntax>[]; | |
| for (final extension in extensions) { | |
| switch (extension) { | |
| case 'autolink': | |
| inlineSyntaxes.add(AutolinkExtensionSyntax()); | |
| break; | |
| case 'strikethrough': | |
| inlineSyntaxes.add(StrikethroughSyntax()); | |
| break; | |
| case 'table': | |
| blockSyntaxes.add(const TableSyntax()); | |
| break; | |
| case 'tagfilter': | |
| enabletagfilter = true; | |
| break; | |
| default: | |
| throw UnimplementedError('Unimplemented extension "$extension"'); | |
| } | |
| } | |
| try { | |
| output = markdownToHtml( | |
| testCase.markdown, | |
| inlineSyntaxes: inlineSyntaxes, | |
| blockSyntaxes: blockSyntaxes, | |
| enableTagfilter: enabletagfilter, | |
| ); | |
| } catch (err, stackTrace) { | |
| if (throwOnError) { | |
| rethrow; | |
| } | |
| if (verboseFail) { | |
| _printVerboseFailure( | |
| config.baseUrl, | |
| 'ERROR', | |
| testCase, | |
| 'Thrown: $err\n$stackTrace', | |
| ); | |
| } | |
| return CompareResult(testCase, null, CompareLevel.error); | |
| } | |
| if (testCase.html == output) { | |
| return CompareResult(testCase, output, CompareLevel.strict); | |
| } | |
| if (config.divergences[testCase.example]?.html == output) { | |
| return CompareResult(testCase, output, CompareLevel.diverged); | |
| } | |
| final expectedParsed = parseFragment(testCase.html); | |
| final actual = parseFragment(output); | |
| final looseMatch = _compareHtml(expectedParsed.children, actual.children); | |
| if (!looseMatch && verboseFail) { | |
| _printVerboseFailure(config.baseUrl, 'FAIL', testCase, output); | |
| } | |
| if (looseMatch && verboseLooseMatch) { | |
| _printVerboseFailure(config.baseUrl, 'LOOSE', testCase, output); | |
| } | |
| return CompareResult( | |
| testCase, | |
| output, | |
| looseMatch ? CompareLevel.loose : CompareLevel.fail, | |
| ); | |
| } | |
| String _indent(String s) => | |
| s.splitMapJoin('\n', onNonMatch: (n) => ' ${whitespaceColor(n)}'); | |
| void _printVerboseFailure( | |
| String baseUrl, | |
| String message, | |
| CommonMarkTestCase testCase, | |
| String actual, | |
| ) { | |
| print( | |
| '$message: $baseUrl#example-${testCase.example} ' | |
| '@ ${testCase.section}', | |
| ); | |
| print('input:'); | |
| print(_indent(testCase.markdown)); | |
| print('expected:'); | |
| print(_indent(testCase.html)); | |
| print('actual:'); | |
| print(_indent(actual)); | |
| print('-----------------------'); | |
| } | |
| /// Compare two DOM trees for equality. | |
| bool _compareHtml( | |
| List<Element> expectedElements, | |
| List<Element> actualElements, | |
| ) { | |
| if (expectedElements.length != actualElements.length) { | |
| return false; | |
| } | |
| for (var childNum = 0; childNum < expectedElements.length; childNum++) { | |
| final expected = expectedElements[childNum]; | |
| final actual = actualElements[childNum]; | |
| if (expected.runtimeType != actual.runtimeType) { | |
| return false; | |
| } | |
| if (expected.localName != actual.localName) { | |
| return false; | |
| } | |
| if (expected.attributes.length != actual.attributes.length) { | |
| return false; | |
| } | |
| final expectedAttrKeys = expected.attributes.keys.toList(); | |
| expectedAttrKeys.sort(); | |
| final actualAttrKeys = actual.attributes.keys.toList(); | |
| actualAttrKeys.sort(); | |
| for (var attrNum = 0; attrNum < actualAttrKeys.length; attrNum++) { | |
| final expectedAttrKey = expectedAttrKeys[attrNum]; | |
| final actualAttrKey = actualAttrKeys[attrNum]; | |
| if (expectedAttrKey != actualAttrKey) { | |
| return false; | |
| } | |
| if (expected.attributes[expectedAttrKey] != | |
| actual.attributes[actualAttrKey]) { | |
| return false; | |
| } | |
| } | |
| final childrenEqual = _compareHtml(expected.children, actual.children); | |
| if (!childrenEqual) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } |