Move snippets package back into flutter repo (#147690)
## Description This moves the snippets package back into the Flutter repo so that API documentation generation can happen without the use of `dart pub global run` because `pub run` doesn't handle concurrency well. The change modifies the dartdoc building process to include building an executable from the snippets tool and installing that in the cache directory for use during docs generation. The snippets tool will reside in dev/snippets, where it originally resided before being moved to https://github.com/flutter/assets-for-api-docs. The snippets code itself is unchanged from the code that is in https://github.com/flutter/assets-for-api-docs/packages/snippets. ## Related Issues - https://github.com/flutter/flutter/issues/144408 - https://github.com/flutter/flutter/issues/147609 - https://github.com/flutter/flutter/pull/147645 ## Tests - Added snippets tests to the overall testing build.
This commit is contained in:
55
dev/snippets/test/configuration_test.dart
Normal file
55
dev/snippets/test/configuration_test.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
// Copyright 2014 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:file/memory.dart';
|
||||
import 'package:snippets/snippets.dart';
|
||||
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
|
||||
|
||||
void main() {
|
||||
group('Configuration', () {
|
||||
final MemoryFileSystem memoryFileSystem = MemoryFileSystem();
|
||||
late SnippetConfiguration config;
|
||||
|
||||
setUp(() {
|
||||
config = FlutterRepoSnippetConfiguration(
|
||||
flutterRoot: memoryFileSystem.directory('/flutter sdk'),
|
||||
filesystem: memoryFileSystem,
|
||||
);
|
||||
});
|
||||
test('config directory is correct', () async {
|
||||
expect(config.configDirectory.path,
|
||||
matches(RegExp(r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config')));
|
||||
});
|
||||
test('skeleton directory is correct', () async {
|
||||
expect(
|
||||
config.skeletonsDirectory.path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons')));
|
||||
});
|
||||
test('templates directory is correct', () async {
|
||||
expect(
|
||||
config.templatesDirectory.path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]templates')));
|
||||
});
|
||||
test('html skeleton file for sample is correct', () async {
|
||||
expect(
|
||||
config.getHtmlSkeletonFile('snippet').path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]snippet.html')));
|
||||
});
|
||||
test('html skeleton file for app with no dartpad is correct', () async {
|
||||
expect(
|
||||
config.getHtmlSkeletonFile('sample').path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]sample.html')));
|
||||
});
|
||||
test('html skeleton file for app with dartpad is correct', () async {
|
||||
expect(
|
||||
config.getHtmlSkeletonFile('dartpad').path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]dartpad-sample.html')));
|
||||
});
|
||||
});
|
||||
}
|
||||
33
dev/snippets/test/fake_process_manager.dart
Normal file
33
dev/snippets/test/fake_process_manager.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
// Copyright 2014 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';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:process/process.dart';
|
||||
|
||||
class FakeProcessManager extends LocalProcessManager {
|
||||
FakeProcessManager(
|
||||
{this.stdout = '', this.stderr = '', this.exitCode = 0, this.pid = 1});
|
||||
|
||||
int runs = 0;
|
||||
String stdout;
|
||||
String stderr;
|
||||
int exitCode;
|
||||
int pid;
|
||||
|
||||
@override
|
||||
ProcessResult runSync(
|
||||
List<Object> command, {
|
||||
String? workingDirectory,
|
||||
Map<String, String>? environment,
|
||||
bool includeParentEnvironment = true,
|
||||
bool runInShell = false,
|
||||
Encoding? stdoutEncoding = systemEncoding,
|
||||
Encoding? stderrEncoding = systemEncoding,
|
||||
}) {
|
||||
runs++;
|
||||
return ProcessResult(pid, exitCode, stdout, stderr);
|
||||
}
|
||||
}
|
||||
428
dev/snippets/test/filesystem_resource_provider.dart
Normal file
428
dev/snippets/test/filesystem_resource_provider.dart
Normal file
@@ -0,0 +1,428 @@
|
||||
// Copyright 2014 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:io' as io;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:analyzer/file_system/file_system.dart';
|
||||
import 'package:analyzer/src/generated/source.dart';
|
||||
import 'package:analyzer/src/source/source_resource.dart';
|
||||
import 'package:file/file.dart' as file;
|
||||
import 'package:file/local.dart' as file;
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:watcher/watcher.dart';
|
||||
|
||||
/// The name of the directory containing plugin specific subfolders used to
|
||||
/// store data across sessions.
|
||||
const String _SERVER_DIR = '.dartServer';
|
||||
|
||||
/// Returns the path to default state location.
|
||||
///
|
||||
/// Generally this is ~/.dartServer. It can be overridden via the
|
||||
/// ANALYZER_STATE_LOCATION_OVERRIDE environment variable, in which case this
|
||||
/// method will return the contents of that environment variable.
|
||||
String? _getStandardStateLocation() {
|
||||
final Map<String, String> env = io.Platform.environment;
|
||||
if (env.containsKey('ANALYZER_STATE_LOCATION_OVERRIDE')) {
|
||||
return env['ANALYZER_STATE_LOCATION_OVERRIDE'];
|
||||
}
|
||||
|
||||
final String? home =
|
||||
io.Platform.isWindows ? env['LOCALAPPDATA'] : env['HOME'];
|
||||
return home != null && io.FileSystemEntity.isDirectorySync(home)
|
||||
? join(home, _SERVER_DIR)
|
||||
: null;
|
||||
}
|
||||
|
||||
/// A `dart:io` based implementation of [ResourceProvider].
|
||||
class FileSystemResourceProvider implements ResourceProvider {
|
||||
FileSystemResourceProvider(this.filesystem, {String? stateLocation})
|
||||
: _stateLocation = stateLocation ?? _getStandardStateLocation();
|
||||
|
||||
static final FileSystemResourceProvider instance =
|
||||
FileSystemResourceProvider(const file.LocalFileSystem());
|
||||
|
||||
/// The path to the base folder where state is stored.
|
||||
final String? _stateLocation;
|
||||
|
||||
final file.FileSystem filesystem;
|
||||
|
||||
@override
|
||||
Context get pathContext => context;
|
||||
|
||||
@override
|
||||
File getFile(String path) {
|
||||
_ensureAbsoluteAndNormalized(path);
|
||||
return _PhysicalFile(filesystem.file(path));
|
||||
}
|
||||
|
||||
@override
|
||||
Folder getFolder(String path) {
|
||||
_ensureAbsoluteAndNormalized(path);
|
||||
return _PhysicalFolder(filesystem.directory(path));
|
||||
}
|
||||
|
||||
@override
|
||||
Resource getResource(String path) {
|
||||
_ensureAbsoluteAndNormalized(path);
|
||||
if (filesystem.isDirectorySync(path)) {
|
||||
return getFolder(path);
|
||||
} else {
|
||||
return getFile(path);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Folder? getStateLocation(String pluginId) {
|
||||
if (_stateLocation != null) {
|
||||
final file.Directory directory =
|
||||
filesystem.directory(join(_stateLocation, pluginId));
|
||||
directory.createSync(recursive: true);
|
||||
return _PhysicalFolder(directory);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The file system abstraction supports only absolute and normalized paths.
|
||||
/// This method is used to validate any input paths to prevent errors later.
|
||||
void _ensureAbsoluteAndNormalized(String path) {
|
||||
assert(() {
|
||||
if (!pathContext.isAbsolute(path)) {
|
||||
throw ArgumentError('Path must be absolute : $path');
|
||||
}
|
||||
if (pathContext.normalize(path) != path) {
|
||||
throw ArgumentError('Path must be normalized : $path');
|
||||
}
|
||||
return true;
|
||||
}());
|
||||
}
|
||||
|
||||
@override
|
||||
Link getLink(String path) {
|
||||
throw UnimplementedError('getLink Not Implemented');
|
||||
}
|
||||
}
|
||||
|
||||
/// A `dart:io` based implementation of [File].
|
||||
class _PhysicalFile extends _PhysicalResource implements File {
|
||||
const _PhysicalFile(io.File super.file);
|
||||
|
||||
@override
|
||||
Stream<WatchEvent> get changes => FileWatcher(_entry.path).events;
|
||||
|
||||
@override
|
||||
int get lengthSync {
|
||||
try {
|
||||
return _file.lengthSync();
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
int get modificationStamp {
|
||||
try {
|
||||
return _file.lastModifiedSync().millisecondsSinceEpoch;
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the underlying file being represented by this wrapper.
|
||||
io.File get _file => _entry as io.File;
|
||||
|
||||
@override
|
||||
File copyTo(Folder parentFolder) {
|
||||
parentFolder.create();
|
||||
final File destination = parentFolder.getChildAssumingFile(shortName);
|
||||
destination.writeAsBytesSync(readAsBytesSync());
|
||||
return destination;
|
||||
}
|
||||
|
||||
@override
|
||||
Source createSource([Uri? uri]) {
|
||||
return FileSource(this, uri ?? pathContext.toUri(path));
|
||||
}
|
||||
|
||||
@override
|
||||
bool isOrContains(String path) {
|
||||
return path == this.path;
|
||||
}
|
||||
|
||||
@override
|
||||
Uint8List readAsBytesSync() {
|
||||
_throwIfWindowsDeviceDriver();
|
||||
try {
|
||||
return _file.readAsBytesSync();
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String readAsStringSync() {
|
||||
_throwIfWindowsDeviceDriver();
|
||||
try {
|
||||
return _file.readAsStringSync();
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
File renameSync(String newPath) {
|
||||
try {
|
||||
return _PhysicalFile(_file.renameSync(newPath));
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
File resolveSymbolicLinksSync() {
|
||||
try {
|
||||
return _PhysicalFile(io.File(_file.resolveSymbolicLinksSync()));
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Uri toUri() => Uri.file(path);
|
||||
|
||||
@override
|
||||
void writeAsBytesSync(List<int> bytes) {
|
||||
try {
|
||||
_file.writeAsBytesSync(bytes);
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void writeAsStringSync(String content) {
|
||||
try {
|
||||
_file.writeAsStringSync(content);
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
ResourceWatcher watch() {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `dart:io` based implementation of [Folder].
|
||||
class _PhysicalFolder extends _PhysicalResource implements Folder {
|
||||
const _PhysicalFolder(io.Directory super.directory);
|
||||
|
||||
@override
|
||||
Stream<WatchEvent> get changes =>
|
||||
DirectoryWatcher(_entry.path).events.handleError((Object error) {},
|
||||
test: (dynamic error) =>
|
||||
error is io.FileSystemException &&
|
||||
// Don't suppress "Directory watcher closed," so the outer
|
||||
// listener can see the interruption & act on it.
|
||||
!error.message
|
||||
.startsWith('Directory watcher closed unexpectedly'));
|
||||
|
||||
@override
|
||||
bool get isRoot {
|
||||
final String parentPath = provider.pathContext.dirname(path);
|
||||
return parentPath == path;
|
||||
}
|
||||
|
||||
/// Return the underlying file being represented by this wrapper.
|
||||
io.Directory get _directory => _entry as io.Directory;
|
||||
|
||||
@override
|
||||
String canonicalizePath(String relPath) {
|
||||
return normalize(join(path, relPath));
|
||||
}
|
||||
|
||||
@override
|
||||
bool contains(String path) {
|
||||
FileSystemResourceProvider.instance._ensureAbsoluteAndNormalized(path);
|
||||
return pathContext.isWithin(this.path, path);
|
||||
}
|
||||
|
||||
@override
|
||||
Folder copyTo(Folder parentFolder) {
|
||||
final Folder destination = parentFolder.getChildAssumingFolder(shortName);
|
||||
destination.create();
|
||||
for (final Resource child in getChildren()) {
|
||||
child.copyTo(destination);
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
|
||||
@override
|
||||
void create() {
|
||||
_directory.createSync(recursive: true);
|
||||
}
|
||||
|
||||
@override
|
||||
Resource getChild(String relPath) {
|
||||
final String canonicalPath = canonicalizePath(relPath);
|
||||
return FileSystemResourceProvider.instance.getResource(canonicalPath);
|
||||
}
|
||||
|
||||
@override
|
||||
_PhysicalFile getChildAssumingFile(String relPath) {
|
||||
final String canonicalPath = canonicalizePath(relPath);
|
||||
final io.File file = io.File(canonicalPath);
|
||||
return _PhysicalFile(file);
|
||||
}
|
||||
|
||||
@override
|
||||
_PhysicalFolder getChildAssumingFolder(String relPath) {
|
||||
final String canonicalPath = canonicalizePath(relPath);
|
||||
final io.Directory directory = io.Directory(canonicalPath);
|
||||
return _PhysicalFolder(directory);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Resource> getChildren() {
|
||||
try {
|
||||
final List<Resource> children = <Resource>[];
|
||||
final io.Directory directory = _entry as io.Directory;
|
||||
final List<io.FileSystemEntity> entries = directory.listSync();
|
||||
final int numEntries = entries.length;
|
||||
for (int i = 0; i < numEntries; i++) {
|
||||
final io.FileSystemEntity entity = entries[i];
|
||||
if (entity is io.Directory) {
|
||||
children.add(_PhysicalFolder(entity));
|
||||
} else if (entity is io.File) {
|
||||
children.add(_PhysicalFile(entity));
|
||||
}
|
||||
}
|
||||
return children;
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool isOrContains(String path) {
|
||||
if (path == this.path) {
|
||||
return true;
|
||||
}
|
||||
return contains(path);
|
||||
}
|
||||
|
||||
@override
|
||||
Folder resolveSymbolicLinksSync() {
|
||||
try {
|
||||
return _PhysicalFolder(
|
||||
io.Directory(_directory.resolveSymbolicLinksSync()));
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Uri toUri() => Uri.directory(path);
|
||||
|
||||
@override
|
||||
ResourceWatcher watch() {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `dart:io` based implementation of [Resource].
|
||||
@immutable
|
||||
abstract class _PhysicalResource implements Resource {
|
||||
const _PhysicalResource(this._entry);
|
||||
|
||||
final io.FileSystemEntity _entry;
|
||||
|
||||
@override
|
||||
bool get exists {
|
||||
try {
|
||||
return _entry.existsSync();
|
||||
} on FileSystemException {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => path.hashCode;
|
||||
|
||||
@override
|
||||
Folder get parent {
|
||||
final String parentPath = pathContext.dirname(path);
|
||||
return _PhysicalFolder(io.Directory(parentPath));
|
||||
}
|
||||
|
||||
@override
|
||||
Folder get parent2 {
|
||||
final String parentPath = pathContext.dirname(path);
|
||||
return _PhysicalFolder(io.Directory(parentPath));
|
||||
}
|
||||
|
||||
@override
|
||||
String get path => _entry.path;
|
||||
|
||||
/// Return the path context used by this resource provider.
|
||||
Context get pathContext => io.Platform.isWindows ? windows : posix;
|
||||
|
||||
@override
|
||||
ResourceProvider get provider => FileSystemResourceProvider.instance;
|
||||
|
||||
@override
|
||||
String get shortName => pathContext.basename(path);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (runtimeType != other.runtimeType) {
|
||||
return false;
|
||||
}
|
||||
// ignore: test_types_in_equals
|
||||
return path == (other as _PhysicalResource).path;
|
||||
}
|
||||
|
||||
@override
|
||||
void delete() {
|
||||
try {
|
||||
_entry.deleteSync(recursive: true);
|
||||
} on io.FileSystemException catch (exception) {
|
||||
throw _wrapException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() => path;
|
||||
|
||||
/// If the operating system is Windows and the resource references one of the
|
||||
/// device drivers, throw a [FileSystemException].
|
||||
///
|
||||
/// https://support.microsoft.com/en-us/kb/74496
|
||||
void _throwIfWindowsDeviceDriver() {
|
||||
if (io.Platform.isWindows) {
|
||||
final String shortName = this.shortName.toUpperCase();
|
||||
if (shortName == r'CON' ||
|
||||
shortName == r'PRN' ||
|
||||
shortName == r'AUX' ||
|
||||
shortName == r'CLOCK$' ||
|
||||
shortName == r'NUL' ||
|
||||
shortName == r'COM1' ||
|
||||
shortName == r'LPT1' ||
|
||||
shortName == r'LPT2' ||
|
||||
shortName == r'LPT3' ||
|
||||
shortName == r'COM2' ||
|
||||
shortName == r'COM3' ||
|
||||
shortName == r'COM4') {
|
||||
throw FileSystemException(
|
||||
path, 'Windows device drivers cannot be read.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FileSystemException _wrapException(io.FileSystemException e) {
|
||||
return FileSystemException(e.path ?? path, e.message);
|
||||
}
|
||||
}
|
||||
103
dev/snippets/test/import_sorter_test.dart
Normal file
103
dev/snippets/test/import_sorter_test.dart
Normal file
@@ -0,0 +1,103 @@
|
||||
// Copyright 2014 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:file/file.dart';
|
||||
import 'package:file/memory.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:pub_semver/pub_semver.dart';
|
||||
import 'package:snippets/snippets.dart';
|
||||
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
|
||||
|
||||
class FakeFlutterInformation extends FlutterInformation {
|
||||
FakeFlutterInformation(this.flutterRoot);
|
||||
|
||||
final Directory flutterRoot;
|
||||
|
||||
@override
|
||||
Map<String, dynamic> getFlutterInformation() {
|
||||
return <String, dynamic>{
|
||||
'flutterRoot': flutterRoot,
|
||||
'frameworkVersion': Version(2, 10, 0),
|
||||
'dartSdkVersion': Version(2, 12, 1),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
late MemoryFileSystem memoryFileSystem = MemoryFileSystem();
|
||||
late Directory tmpDir;
|
||||
|
||||
setUp(() {
|
||||
// Create a new filesystem.
|
||||
memoryFileSystem = MemoryFileSystem();
|
||||
tmpDir = memoryFileSystem.systemTempDirectory
|
||||
.createTempSync('flutter_snippets_test.');
|
||||
final Directory flutterRoot =
|
||||
memoryFileSystem.directory(path.join(tmpDir.absolute.path, 'flutter'));
|
||||
FlutterInformation.instance = FakeFlutterInformation(flutterRoot);
|
||||
});
|
||||
|
||||
test('Sorting packages works', () async {
|
||||
final String result = sortImports('''
|
||||
// Unit comment
|
||||
|
||||
// third import
|
||||
import 'packages:gamma/gamma.dart'; // third
|
||||
|
||||
// second import
|
||||
import 'packages:beta/beta.dart'; // second
|
||||
|
||||
// first import
|
||||
import 'packages:alpha/alpha.dart'; // first
|
||||
|
||||
void main() {}
|
||||
''');
|
||||
expect(result, equals('''
|
||||
// Unit comment
|
||||
|
||||
// first import
|
||||
import 'packages:alpha/alpha.dart'; // first
|
||||
// second import
|
||||
import 'packages:beta/beta.dart'; // second
|
||||
// third import
|
||||
import 'packages:gamma/gamma.dart'; // third
|
||||
|
||||
void main() {}
|
||||
'''));
|
||||
});
|
||||
test('Sorting dart and packages works', () async {
|
||||
final String result = sortImports('''
|
||||
// Unit comment
|
||||
|
||||
// third import
|
||||
import 'packages:gamma/gamma.dart'; // third
|
||||
|
||||
// second import
|
||||
import 'packages:beta/beta.dart'; // second
|
||||
|
||||
// first import
|
||||
import 'packages:alpha/alpha.dart'; // first
|
||||
|
||||
// first dart
|
||||
import 'dart:async';
|
||||
|
||||
void main() {}
|
||||
''');
|
||||
expect(result, equals('''
|
||||
// Unit comment
|
||||
|
||||
// first dart
|
||||
import 'dart:async';
|
||||
|
||||
// first import
|
||||
import 'packages:alpha/alpha.dart'; // first
|
||||
// second import
|
||||
import 'packages:beta/beta.dart'; // second
|
||||
// third import
|
||||
import 'packages:gamma/gamma.dart'; // third
|
||||
|
||||
void main() {}
|
||||
'''));
|
||||
});
|
||||
}
|
||||
334
dev/snippets/test/snippet_parser_test.dart
Normal file
334
dev/snippets/test/snippet_parser_test.dart
Normal file
@@ -0,0 +1,334 @@
|
||||
// Copyright 2014 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:file/file.dart';
|
||||
import 'package:file/memory.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:pub_semver/pub_semver.dart';
|
||||
import 'package:snippets/snippets.dart';
|
||||
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
|
||||
|
||||
import 'filesystem_resource_provider.dart';
|
||||
|
||||
class FakeFlutterInformation extends FlutterInformation {
|
||||
FakeFlutterInformation(this.flutterRoot);
|
||||
|
||||
final Directory flutterRoot;
|
||||
|
||||
@override
|
||||
Directory getFlutterRoot() {
|
||||
return flutterRoot;
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> getFlutterInformation() {
|
||||
return <String, dynamic>{
|
||||
'flutterRoot': flutterRoot,
|
||||
'frameworkVersion': Version(2, 10, 0),
|
||||
'dartSdkVersion': Version(2, 12, 1),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('Parser', () {
|
||||
late MemoryFileSystem memoryFileSystem = MemoryFileSystem();
|
||||
late FlutterRepoSnippetConfiguration configuration;
|
||||
late SnippetGenerator generator;
|
||||
late Directory tmpDir;
|
||||
late File template;
|
||||
late Directory flutterRoot;
|
||||
|
||||
void writeSkeleton(String type) {
|
||||
switch (type) {
|
||||
case 'dartpad':
|
||||
configuration.getHtmlSkeletonFile('dartpad').writeAsStringSync('''
|
||||
<div>HTML Bits (DartPad-style)</div>
|
||||
<iframe class="snippet-dartpad" src="https://dartpad.dev/embed-flutter.html?split=60&run=true&sample_id={{id}}&sample_channel={{channel}}"></iframe>
|
||||
<div>More HTML Bits</div>
|
||||
''');
|
||||
case 'sample':
|
||||
case 'snippet':
|
||||
configuration.getHtmlSkeletonFile(type).writeAsStringSync('''
|
||||
<div>HTML Bits</div>
|
||||
{{description}}
|
||||
<pre>{{code}}</pre>
|
||||
<pre>{{app}}</pre>
|
||||
<div>More HTML Bits</div>
|
||||
''');
|
||||
}
|
||||
}
|
||||
|
||||
setUp(() {
|
||||
// Create a new filesystem.
|
||||
memoryFileSystem = MemoryFileSystem();
|
||||
tmpDir = memoryFileSystem.systemTempDirectory
|
||||
.createTempSync('flutter_snippets_test.');
|
||||
flutterRoot = memoryFileSystem
|
||||
.directory(path.join(tmpDir.absolute.path, 'flutter'));
|
||||
configuration = FlutterRepoSnippetConfiguration(
|
||||
flutterRoot: flutterRoot, filesystem: memoryFileSystem);
|
||||
configuration.templatesDirectory.createSync(recursive: true);
|
||||
configuration.skeletonsDirectory.createSync(recursive: true);
|
||||
template = memoryFileSystem.file(
|
||||
path.join(configuration.templatesDirectory.path, 'template.tmpl'));
|
||||
template.writeAsStringSync('''
|
||||
// Flutter code sample for {{element}}
|
||||
|
||||
{{description}}
|
||||
|
||||
{{code-my-preamble}}
|
||||
|
||||
{{code}}
|
||||
''');
|
||||
<String>['dartpad', 'sample', 'snippet'].forEach(writeSkeleton);
|
||||
FlutterInformation.instance = FakeFlutterInformation(flutterRoot);
|
||||
generator = SnippetGenerator(
|
||||
configuration: configuration,
|
||||
filesystem: memoryFileSystem,
|
||||
flutterRoot: configuration.templatesDirectory.parent);
|
||||
});
|
||||
|
||||
test('parses from comments', () async {
|
||||
final File inputFile = _createSnippetSourceFile(tmpDir, memoryFileSystem);
|
||||
final Iterable<SourceElement> elements = getFileElements(inputFile,
|
||||
resourceProvider: FileSystemResourceProvider(memoryFileSystem));
|
||||
expect(elements, isNotEmpty);
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
sampleParser.parseFromComments(elements);
|
||||
sampleParser.parseAndAddAssumptions(elements, inputFile);
|
||||
expect(elements.length, equals(7));
|
||||
int sampleCount = 0;
|
||||
for (final SourceElement element in elements) {
|
||||
expect(element.samples.length, greaterThanOrEqualTo(1));
|
||||
sampleCount += element.samples.length;
|
||||
final String code = generator.generateCode(element.samples.first);
|
||||
expect(code, contains('// Description'));
|
||||
expect(
|
||||
code,
|
||||
contains(RegExp(
|
||||
'''^String elementName = '${element.elementName}';\$''',
|
||||
multiLine: true)));
|
||||
final String html = generator.generateHtml(element.samples.first);
|
||||
expect(
|
||||
html,
|
||||
contains(RegExp(
|
||||
'''^<pre>String elementName = '${element.elementName}';.*\$''',
|
||||
multiLine: true)));
|
||||
expect(
|
||||
html,
|
||||
contains(
|
||||
'<div class="snippet-description">{@end-inject-html}Description{@inject-html}</div>\n'));
|
||||
}
|
||||
expect(sampleCount, equals(8));
|
||||
});
|
||||
test('parses dartpad samples from comments', () async {
|
||||
final File inputFile =
|
||||
_createDartpadSourceFile(tmpDir, memoryFileSystem, flutterRoot);
|
||||
final Iterable<SourceElement> elements = getFileElements(inputFile,
|
||||
resourceProvider: FileSystemResourceProvider(memoryFileSystem));
|
||||
expect(elements, isNotEmpty);
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
sampleParser.parseFromComments(elements);
|
||||
expect(elements.length, equals(1));
|
||||
int sampleCount = 0;
|
||||
for (final SourceElement element in elements) {
|
||||
expect(element.samples.length, greaterThanOrEqualTo(1));
|
||||
sampleCount += element.samples.length;
|
||||
final String code = generator.generateCode(element.samples.first);
|
||||
expect(code, contains('// Description'));
|
||||
expect(
|
||||
code,
|
||||
contains(RegExp('^void ${element.name}Sample\\(\\) \\{.*\$',
|
||||
multiLine: true)));
|
||||
final String html = generator.generateHtml(element.samples.first);
|
||||
expect(
|
||||
html,
|
||||
contains(RegExp(
|
||||
'''^<iframe class="snippet-dartpad" src="https://dartpad.dev/.*sample_id=${element.name}.0.*></iframe>.*\$''',
|
||||
multiLine: true)));
|
||||
}
|
||||
expect(sampleCount, equals(1));
|
||||
});
|
||||
test('parses dartpad samples from linked file', () async {
|
||||
final File inputFile = _createDartpadSourceFile(
|
||||
tmpDir, memoryFileSystem, flutterRoot,
|
||||
linked: true);
|
||||
final Iterable<SourceElement> elements = getFileElements(inputFile,
|
||||
resourceProvider: FileSystemResourceProvider(memoryFileSystem));
|
||||
expect(elements, isNotEmpty);
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
sampleParser.parseFromComments(elements);
|
||||
expect(elements.length, equals(1));
|
||||
int sampleCount = 0;
|
||||
for (final SourceElement element in elements) {
|
||||
expect(element.samples.length, greaterThanOrEqualTo(1));
|
||||
sampleCount += element.samples.length;
|
||||
final String code =
|
||||
generator.generateCode(element.samples.first, formatOutput: false);
|
||||
expect(code, contains('// Description'));
|
||||
expect(
|
||||
code,
|
||||
contains(RegExp('^void ${element.name}Sample\\(\\) \\{.*\$',
|
||||
multiLine: true)));
|
||||
final String html = generator.generateHtml(element.samples.first);
|
||||
expect(
|
||||
html,
|
||||
contains(RegExp(
|
||||
'''^<iframe class="snippet-dartpad" src="https://dartpad.dev/.*sample_id=${element.name}.0.*></iframe>.*\$''',
|
||||
multiLine: true)));
|
||||
}
|
||||
expect(sampleCount, equals(1));
|
||||
});
|
||||
test('parses assumptions', () async {
|
||||
final File inputFile = _createSnippetSourceFile(tmpDir, memoryFileSystem);
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
final List<SourceLine> assumptions =
|
||||
sampleParser.parseAssumptions(inputFile);
|
||||
expect(assumptions.length, equals(1));
|
||||
expect(assumptions.first.text, equals('int integer = 3;'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
File _createSnippetSourceFile(Directory tmpDir, FileSystem filesystem) {
|
||||
return filesystem.file(path.join(tmpDir.absolute.path, 'snippet_in.dart'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync(r'''
|
||||
// Copyright
|
||||
|
||||
// @dart = 2.12
|
||||
|
||||
import 'foo.dart';
|
||||
|
||||
// Examples can assume:
|
||||
// int integer = 3;
|
||||
|
||||
/// Top level variable comment
|
||||
///
|
||||
/// {@tool snippet}
|
||||
/// Description
|
||||
/// ```dart
|
||||
/// String elementName = 'topLevelVariable';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
int topLevelVariable = 4;
|
||||
|
||||
/// Top level function comment
|
||||
///
|
||||
/// {@tool snippet}
|
||||
/// Description
|
||||
/// ```dart
|
||||
/// String elementName = 'topLevelFunction';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
int topLevelFunction() {
|
||||
return integer;
|
||||
}
|
||||
|
||||
/// Class comment
|
||||
///
|
||||
/// {@tool snippet}
|
||||
/// Description
|
||||
/// ```dart
|
||||
/// String elementName = 'DocumentedClass';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
/// {@tool snippet}
|
||||
/// Description2
|
||||
/// ```dart
|
||||
/// String elementName = 'DocumentedClass';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
class DocumentedClass {
|
||||
/// Constructor comment
|
||||
/// {@tool snippet}
|
||||
/// Description
|
||||
/// ```dart
|
||||
/// String elementName = 'DocumentedClass';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
const DocumentedClass();
|
||||
|
||||
/// Named constructor comment
|
||||
/// {@tool snippet}
|
||||
/// Description
|
||||
/// ```dart
|
||||
/// String elementName = 'DocumentedClass.name';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
const DocumentedClass.name();
|
||||
|
||||
/// Member variable comment
|
||||
/// {@tool snippet}
|
||||
/// Description
|
||||
/// ```dart
|
||||
/// String elementName = 'DocumentedClass.intMember';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
int intMember;
|
||||
|
||||
/// Member comment
|
||||
/// {@tool snippet}
|
||||
/// Description
|
||||
/// ```dart
|
||||
/// String elementName = 'DocumentedClass.member';
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
void member() {}
|
||||
}
|
||||
''');
|
||||
}
|
||||
|
||||
File _createDartpadSourceFile(
|
||||
Directory tmpDir, FileSystem filesystem, Directory flutterRoot,
|
||||
{bool linked = false}) {
|
||||
final File linkedFile =
|
||||
filesystem.file(path.join(flutterRoot.absolute.path, 'linked_file.dart'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync('''
|
||||
// Copyright
|
||||
|
||||
import 'foo.dart';
|
||||
|
||||
// Description
|
||||
|
||||
void DocumentedClassSample() {
|
||||
String elementName = 'DocumentedClass';
|
||||
}
|
||||
''');
|
||||
|
||||
final String source = linked
|
||||
? '''
|
||||
/// ** See code in ${path.relative(linkedFile.path, from: flutterRoot.absolute.path)} **'''
|
||||
: '''
|
||||
/// ```dart
|
||||
/// void DocumentedClassSample() {
|
||||
/// String elementName = 'DocumentedClass';
|
||||
/// }
|
||||
/// ```''';
|
||||
|
||||
return filesystem.file(path.join(tmpDir.absolute.path, 'snippet_in.dart'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync('''
|
||||
// Copyright
|
||||
|
||||
// @dart = 2.12
|
||||
|
||||
import 'foo.dart';
|
||||
|
||||
/// Class comment
|
||||
///
|
||||
/// {@tool dartpad --template=template}
|
||||
/// Description
|
||||
$source
|
||||
/// {@end-tool}
|
||||
class DocumentedClass {}
|
||||
''');
|
||||
}
|
||||
438
dev/snippets/test/snippets_test.dart
Normal file
438
dev/snippets/test/snippets_test.dart
Normal file
@@ -0,0 +1,438 @@
|
||||
// Copyright 2014 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';
|
||||
|
||||
import 'package:file/file.dart';
|
||||
import 'package:file/memory.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:platform/platform.dart';
|
||||
import 'package:pub_semver/pub_semver.dart';
|
||||
import 'package:snippets/snippets.dart';
|
||||
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
|
||||
|
||||
import '../bin/snippets.dart' as snippets_main;
|
||||
import 'fake_process_manager.dart';
|
||||
|
||||
class FakeFlutterInformation extends FlutterInformation {
|
||||
FakeFlutterInformation(this.flutterRoot);
|
||||
|
||||
final Directory flutterRoot;
|
||||
|
||||
@override
|
||||
Directory getFlutterRoot() {
|
||||
return flutterRoot;
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> getFlutterInformation() {
|
||||
return <String, dynamic>{
|
||||
'flutterRoot': flutterRoot,
|
||||
'frameworkVersion': Version(2, 10, 0),
|
||||
'dartSdkVersion': Version(2, 12, 1),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('Generator', () {
|
||||
late MemoryFileSystem memoryFileSystem = MemoryFileSystem();
|
||||
late FlutterRepoSnippetConfiguration configuration;
|
||||
late SnippetGenerator generator;
|
||||
late Directory tmpDir;
|
||||
late File template;
|
||||
|
||||
void writeSkeleton(String type) {
|
||||
switch (type) {
|
||||
case 'dartpad':
|
||||
configuration.getHtmlSkeletonFile('dartpad').writeAsStringSync('''
|
||||
<div>HTML Bits (DartPad-style)</div>
|
||||
<iframe class="snippet-dartpad" src="https://dartpad.dev/embed-flutter.html?split=60&run=true&sample_id={{id}}&sample_channel={{channel}}"></iframe>
|
||||
<div>More HTML Bits</div>
|
||||
''');
|
||||
case 'sample':
|
||||
case 'snippet':
|
||||
configuration.getHtmlSkeletonFile(type).writeAsStringSync('''
|
||||
<div>HTML Bits</div>
|
||||
{{description}}
|
||||
<pre>{{code}}</pre>
|
||||
<pre>{{app}}</pre>
|
||||
<div>More HTML Bits</div>
|
||||
''');
|
||||
}
|
||||
}
|
||||
|
||||
setUp(() {
|
||||
// Create a new filesystem.
|
||||
memoryFileSystem = MemoryFileSystem();
|
||||
tmpDir = memoryFileSystem.systemTempDirectory
|
||||
.createTempSync('flutter_snippets_test.');
|
||||
configuration = FlutterRepoSnippetConfiguration(
|
||||
flutterRoot: memoryFileSystem
|
||||
.directory(path.join(tmpDir.absolute.path, 'flutter')),
|
||||
filesystem: memoryFileSystem);
|
||||
configuration.templatesDirectory.createSync(recursive: true);
|
||||
configuration.skeletonsDirectory.createSync(recursive: true);
|
||||
template = memoryFileSystem.file(
|
||||
path.join(configuration.templatesDirectory.path, 'template.tmpl'));
|
||||
template.writeAsStringSync('''
|
||||
// Flutter code sample for {{element}}
|
||||
|
||||
{{description}}
|
||||
|
||||
{{code-my-preamble}}
|
||||
|
||||
{{code}}
|
||||
''');
|
||||
<String>['dartpad', 'sample', 'snippet'].forEach(writeSkeleton);
|
||||
FlutterInformation.instance =
|
||||
FakeFlutterInformation(configuration.flutterRoot);
|
||||
generator = SnippetGenerator(
|
||||
configuration: configuration,
|
||||
filesystem: memoryFileSystem,
|
||||
flutterRoot: configuration.templatesDirectory.parent);
|
||||
});
|
||||
|
||||
test('generates samples', () async {
|
||||
final File inputFile = memoryFileSystem
|
||||
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync(r'''
|
||||
A description of the snippet.
|
||||
|
||||
On several lines.
|
||||
|
||||
```my-dart_language my-preamble
|
||||
const String name = 'snippet';
|
||||
```
|
||||
|
||||
```dart
|
||||
void main() {
|
||||
print('The actual $name.');
|
||||
}
|
||||
```
|
||||
''');
|
||||
final File outputFile = memoryFileSystem
|
||||
.file(path.join(tmpDir.absolute.path, 'snippet_out.txt'));
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
|
||||
const int sourceLine = 222;
|
||||
final SourceElement element = sampleParser.parseFromDartdocToolFile(
|
||||
inputFile,
|
||||
element: 'MyElement',
|
||||
startLine: sourceLine,
|
||||
sourceFile: memoryFileSystem.file(sourcePath),
|
||||
type: 'sample',
|
||||
);
|
||||
|
||||
expect(element.samples, isNotEmpty);
|
||||
element.samples.first.metadata.addAll(<String, Object?>{
|
||||
'channel': 'stable',
|
||||
});
|
||||
final String code = generator.generateCode(
|
||||
element.samples.first,
|
||||
output: outputFile,
|
||||
);
|
||||
expect(code, contains('// Flutter code sample for MyElement'));
|
||||
final String html = generator.generateHtml(
|
||||
element.samples.first,
|
||||
);
|
||||
expect(html, contains('<div>HTML Bits</div>'));
|
||||
expect(html, contains('<div>More HTML Bits</div>'));
|
||||
expect(html, contains(r'print('The actual $name.');'));
|
||||
expect(html, contains('A description of the snippet.\n'));
|
||||
expect(html, isNot(contains('sample_channel=stable')));
|
||||
expect(
|
||||
html,
|
||||
contains('A description of the snippet.\n'
|
||||
'\n'
|
||||
'On several lines.{@inject-html}</div>'));
|
||||
expect(html, contains('void main() {'));
|
||||
|
||||
final String outputContents = outputFile.readAsStringSync();
|
||||
expect(outputContents, contains('// Flutter code sample for MyElement'));
|
||||
expect(outputContents, contains('A description of the snippet.'));
|
||||
expect(outputContents, contains('void main() {'));
|
||||
expect(outputContents, contains("const String name = 'snippet';"));
|
||||
});
|
||||
|
||||
test('generates snippets', () async {
|
||||
final File inputFile = memoryFileSystem
|
||||
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync(r'''
|
||||
A description of the snippet.
|
||||
|
||||
On several lines.
|
||||
|
||||
```code
|
||||
void main() {
|
||||
print('The actual $name.');
|
||||
}
|
||||
```
|
||||
''');
|
||||
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
|
||||
const int sourceLine = 222;
|
||||
final SourceElement element = sampleParser.parseFromDartdocToolFile(
|
||||
inputFile,
|
||||
element: 'MyElement',
|
||||
startLine: sourceLine,
|
||||
sourceFile: memoryFileSystem.file(sourcePath),
|
||||
type: 'snippet',
|
||||
);
|
||||
expect(element.samples, isNotEmpty);
|
||||
element.samples.first.metadata.addAll(<String, Object>{
|
||||
'channel': 'stable',
|
||||
});
|
||||
final String code = generator.generateCode(element.samples.first);
|
||||
expect(code, contains('// A description of the snippet.'));
|
||||
final String html = generator.generateHtml(element.samples.first);
|
||||
expect(html, contains('<div>HTML Bits</div>'));
|
||||
expect(html, contains('<div>More HTML Bits</div>'));
|
||||
expect(html, contains(r' print('The actual $name.');'));
|
||||
expect(
|
||||
html,
|
||||
contains(
|
||||
'<div class="snippet-description">{@end-inject-html}A description of the snippet.\n\n'
|
||||
'On several lines.{@inject-html}</div>\n'));
|
||||
expect(html, contains('main() {'));
|
||||
});
|
||||
|
||||
test('generates dartpad samples', () async {
|
||||
final File inputFile = memoryFileSystem
|
||||
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync(r'''
|
||||
A description of the snippet.
|
||||
|
||||
On several lines.
|
||||
|
||||
```code
|
||||
void main() {
|
||||
print('The actual $name.');
|
||||
}
|
||||
```
|
||||
''');
|
||||
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
|
||||
const int sourceLine = 222;
|
||||
final SourceElement element = sampleParser.parseFromDartdocToolFile(
|
||||
inputFile,
|
||||
element: 'MyElement',
|
||||
startLine: sourceLine,
|
||||
sourceFile: memoryFileSystem.file(sourcePath),
|
||||
type: 'dartpad',
|
||||
);
|
||||
expect(element.samples, isNotEmpty);
|
||||
element.samples.first.metadata.addAll(<String, Object>{
|
||||
'channel': 'stable',
|
||||
});
|
||||
final String code = generator.generateCode(element.samples.first);
|
||||
expect(code, contains('// Flutter code sample for MyElement'));
|
||||
final String html = generator.generateHtml(element.samples.first);
|
||||
expect(html, contains('<div>HTML Bits (DartPad-style)</div>'));
|
||||
expect(html, contains('<div>More HTML Bits</div>'));
|
||||
expect(
|
||||
html,
|
||||
contains(
|
||||
'<iframe class="snippet-dartpad" src="https://dartpad.dev/embed-flutter.html?split=60&run=true&sample_id=MyElement.0&sample_channel=stable"></iframe>\n'));
|
||||
});
|
||||
|
||||
test('generates sample metadata', () async {
|
||||
final File inputFile = memoryFileSystem
|
||||
.file(path.join(tmpDir.absolute.path, 'snippet_in.txt'))
|
||||
..createSync(recursive: true)
|
||||
..writeAsStringSync(r'''
|
||||
A description of the snippet.
|
||||
|
||||
On several lines.
|
||||
|
||||
```dart
|
||||
void main() {
|
||||
print('The actual $name.');
|
||||
}
|
||||
```
|
||||
''');
|
||||
|
||||
final File outputFile = memoryFileSystem
|
||||
.file(path.join(tmpDir.absolute.path, 'snippet_out.dart'));
|
||||
final File expectedMetadataFile = memoryFileSystem
|
||||
.file(path.join(tmpDir.absolute.path, 'snippet_out.json'));
|
||||
|
||||
final SnippetDartdocParser sampleParser =
|
||||
SnippetDartdocParser(memoryFileSystem);
|
||||
const String sourcePath = 'packages/flutter/lib/src/widgets/foo.dart';
|
||||
const int sourceLine = 222;
|
||||
final SourceElement element = sampleParser.parseFromDartdocToolFile(
|
||||
inputFile,
|
||||
element: 'MyElement',
|
||||
startLine: sourceLine,
|
||||
sourceFile: memoryFileSystem.file(sourcePath),
|
||||
type: 'sample',
|
||||
);
|
||||
expect(element.samples, isNotEmpty);
|
||||
element.samples.first.metadata
|
||||
.addAll(<String, Object>{'channel': 'stable'});
|
||||
generator.generateCode(element.samples.first, output: outputFile);
|
||||
expect(expectedMetadataFile.existsSync(), isTrue);
|
||||
final Map<String, dynamic> json =
|
||||
jsonDecode(expectedMetadataFile.readAsStringSync())
|
||||
as Map<String, dynamic>;
|
||||
expect(json['id'], equals('MyElement.0'));
|
||||
expect(json['channel'], equals('stable'));
|
||||
expect(json['file'], equals('snippet_out.dart'));
|
||||
expect(json['description'],
|
||||
equals('A description of the snippet.\n\nOn several lines.'));
|
||||
expect(json['sourcePath'],
|
||||
equals('packages/flutter/lib/src/widgets/foo.dart'));
|
||||
});
|
||||
});
|
||||
|
||||
group('snippets command line argument test', () {
|
||||
late MemoryFileSystem memoryFileSystem = MemoryFileSystem();
|
||||
late Directory tmpDir;
|
||||
late Directory flutterRoot;
|
||||
late FakeProcessManager fakeProcessManager;
|
||||
|
||||
setUp(() {
|
||||
fakeProcessManager = FakeProcessManager();
|
||||
memoryFileSystem = MemoryFileSystem();
|
||||
tmpDir = memoryFileSystem.systemTempDirectory
|
||||
.createTempSync('flutter_snippets_test.');
|
||||
flutterRoot = memoryFileSystem
|
||||
.directory(path.join(tmpDir.absolute.path, 'flutter'))
|
||||
..createSync(recursive: true);
|
||||
});
|
||||
|
||||
test('command line arguments are parsed and passed to generator', () {
|
||||
final FakePlatform platform = FakePlatform(environment: <String, String>{
|
||||
'PACKAGE_NAME': 'dart:ui',
|
||||
'LIBRARY_NAME': 'library',
|
||||
'ELEMENT_NAME': 'element',
|
||||
'FLUTTER_ROOT': flutterRoot.absolute.path,
|
||||
// The details here don't really matter other than the flutter root.
|
||||
'FLUTTER_VERSION': '''
|
||||
{
|
||||
"frameworkVersion": "2.5.0-6.0.pre.55",
|
||||
"channel": "use_snippets_pkg",
|
||||
"repositoryUrl": "git@github.com:flutter/flutter.git",
|
||||
"frameworkRevision": "fec4641e1c88923ecd6c969e2ff8a0dd12dc0875",
|
||||
"frameworkCommitDate": "2021-08-11 15:19:48 -0700",
|
||||
"engineRevision": "d8bbebed60a77b3d4fe9c840dc94dfbce159d951",
|
||||
"dartSdkVersion": "2.14.0 (build 2.14.0-393.0.dev)",
|
||||
"flutterRoot": "${flutterRoot.absolute.path}"
|
||||
}''',
|
||||
});
|
||||
final FlutterInformation flutterInformation = FlutterInformation(
|
||||
filesystem: memoryFileSystem,
|
||||
processManager: fakeProcessManager,
|
||||
platform: platform,
|
||||
);
|
||||
FlutterInformation.instance = flutterInformation;
|
||||
MockSnippetGenerator mockSnippetGenerator = MockSnippetGenerator();
|
||||
snippets_main.snippetGenerator = mockSnippetGenerator;
|
||||
String errorMessage = '';
|
||||
errorExit = (String message) {
|
||||
errorMessage = message;
|
||||
};
|
||||
|
||||
snippets_main.platform = platform;
|
||||
snippets_main.filesystem = memoryFileSystem;
|
||||
snippets_main.processManager = fakeProcessManager;
|
||||
final File input = memoryFileSystem
|
||||
.file(tmpDir.childFile('input.snippet'))
|
||||
..writeAsString('/// Test file');
|
||||
snippets_main.main(
|
||||
<String>['--input=${input.absolute.path}', '--template=template']);
|
||||
|
||||
final Map<String, dynamic> metadata =
|
||||
mockSnippetGenerator.sample.metadata;
|
||||
// Ignore the channel, because channel is really just the branch, and will be
|
||||
// different on development workstations.
|
||||
metadata.remove('channel');
|
||||
expect(
|
||||
metadata,
|
||||
equals(<String, dynamic>{
|
||||
'id': 'dart_ui.library.element',
|
||||
'element': 'element',
|
||||
'sourcePath': 'unknown.dart',
|
||||
'sourceLine': 1,
|
||||
'serial': '',
|
||||
'package': 'dart:ui',
|
||||
'library': 'library',
|
||||
}));
|
||||
|
||||
snippets_main.main(<String>[]);
|
||||
expect(
|
||||
errorMessage,
|
||||
equals(
|
||||
'The --input option must be specified, either on the command line, or in the INPUT environment variable.'));
|
||||
errorMessage = '';
|
||||
|
||||
snippets_main
|
||||
.main(<String>['--input=${input.absolute.path}', '--type=snippet']);
|
||||
expect(errorMessage, equals(''));
|
||||
errorMessage = '';
|
||||
|
||||
mockSnippetGenerator = MockSnippetGenerator();
|
||||
snippets_main.snippetGenerator = mockSnippetGenerator;
|
||||
snippets_main.main(<String>[
|
||||
'--input=${input.absolute.path}',
|
||||
'--type=snippet',
|
||||
'--no-format-output'
|
||||
]);
|
||||
expect(mockSnippetGenerator.formatOutput, equals(false));
|
||||
errorMessage = '';
|
||||
|
||||
input.deleteSync();
|
||||
snippets_main.main(
|
||||
<String>['--input=${input.absolute.path}', '--template=template']);
|
||||
expect(errorMessage,
|
||||
equals('The input file ${input.absolute.path} does not exist.'));
|
||||
errorMessage = '';
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class MockSnippetGenerator extends SnippetGenerator {
|
||||
late CodeSample sample;
|
||||
File? output;
|
||||
String? copyright;
|
||||
String? description;
|
||||
late bool formatOutput;
|
||||
late bool addSectionMarkers;
|
||||
late bool includeAssumptions;
|
||||
|
||||
@override
|
||||
String generateCode(
|
||||
CodeSample sample, {
|
||||
File? output,
|
||||
String? copyright,
|
||||
String? description,
|
||||
bool formatOutput = true,
|
||||
bool addSectionMarkers = false,
|
||||
bool includeAssumptions = false,
|
||||
}) {
|
||||
this.sample = sample;
|
||||
this.output = output;
|
||||
this.copyright = copyright;
|
||||
this.description = description;
|
||||
this.formatOutput = formatOutput;
|
||||
this.addSectionMarkers = addSectionMarkers;
|
||||
this.includeAssumptions = includeAssumptions;
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
@override
|
||||
String generateHtml(CodeSample sample) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
87
dev/snippets/test/util_test.dart
Normal file
87
dev/snippets/test/util_test.dart
Normal file
@@ -0,0 +1,87 @@
|
||||
// Copyright 2014 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:io';
|
||||
|
||||
import 'package:file/memory.dart';
|
||||
import 'package:platform/platform.dart';
|
||||
import 'package:pub_semver/pub_semver.dart';
|
||||
import 'package:snippets/snippets.dart';
|
||||
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
|
||||
|
||||
import 'fake_process_manager.dart';
|
||||
|
||||
const String testVersionInfo = r'''
|
||||
{
|
||||
"frameworkVersion": "2.5.0-2.0.pre.63",
|
||||
"channel": "master",
|
||||
"repositoryUrl": "git@github.com:flutter/flutter.git",
|
||||
"frameworkRevision": "9b2f6f7f9ab96bb3302f81b814a094f33023e79a",
|
||||
"frameworkCommitDate": "2021-07-28 13:03:40 -0700",
|
||||
"engineRevision": "0ed62a16f36348e97b2baadd8ccfec3825f80c5d",
|
||||
"dartSdkVersion": "2.14.0 (build 2.14.0-360.0.dev)",
|
||||
"flutterRoot": "/home/user/flutter"
|
||||
}
|
||||
''';
|
||||
|
||||
void main() {
|
||||
group('FlutterInformation', () {
|
||||
late FakeProcessManager fakeProcessManager;
|
||||
late FakePlatform fakePlatform;
|
||||
late MemoryFileSystem memoryFileSystem;
|
||||
late FlutterInformation flutterInformation;
|
||||
|
||||
setUp(() {
|
||||
fakeProcessManager = FakeProcessManager();
|
||||
memoryFileSystem = MemoryFileSystem();
|
||||
fakePlatform = FakePlatform(environment: <String, String>{});
|
||||
flutterInformation = FlutterInformation(
|
||||
filesystem: memoryFileSystem,
|
||||
processManager: fakeProcessManager,
|
||||
platform: fakePlatform,
|
||||
);
|
||||
});
|
||||
|
||||
test('calls out to flutter if FLUTTER_VERSION is not set', () async {
|
||||
fakeProcessManager.stdout = testVersionInfo;
|
||||
final Map<String, dynamic> info =
|
||||
flutterInformation.getFlutterInformation();
|
||||
expect(fakeProcessManager.runs, equals(1));
|
||||
expect(
|
||||
info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
|
||||
});
|
||||
test("doesn't call out to flutter if FLUTTER_VERSION is set", () async {
|
||||
fakePlatform.environment['FLUTTER_VERSION'] = testVersionInfo;
|
||||
final Map<String, dynamic> info =
|
||||
flutterInformation.getFlutterInformation();
|
||||
expect(fakeProcessManager.runs, equals(0));
|
||||
expect(
|
||||
info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
|
||||
});
|
||||
test('getFlutterRoot calls out to flutter if FLUTTER_ROOT is not set',
|
||||
() async {
|
||||
fakeProcessManager.stdout = testVersionInfo;
|
||||
final Directory root = flutterInformation.getFlutterRoot();
|
||||
expect(fakeProcessManager.runs, equals(1));
|
||||
expect(root.path, equals('/home/user/flutter'));
|
||||
});
|
||||
test("getFlutterRoot doesn't call out to flutter if FLUTTER_ROOT is set",
|
||||
() async {
|
||||
fakePlatform.environment['FLUTTER_ROOT'] = '/home/user/flutter';
|
||||
final Directory root = flutterInformation.getFlutterRoot();
|
||||
expect(fakeProcessManager.runs, equals(0));
|
||||
expect(root.path, equals('/home/user/flutter'));
|
||||
});
|
||||
test('parses version properly', () async {
|
||||
fakePlatform.environment['FLUTTER_VERSION'] = testVersionInfo;
|
||||
final Map<String, dynamic> info =
|
||||
flutterInformation.getFlutterInformation();
|
||||
expect(info['frameworkVersion'], isNotNull);
|
||||
expect(
|
||||
info['frameworkVersion'], equals(Version.parse('2.5.0-2.0.pre.63')));
|
||||
expect(info['dartSdkVersion'], isNotNull);
|
||||
expect(info['dartSdkVersion'], equals(Version.parse('2.14.0-360.0.dev')));
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user