fileContextForTest function

Future<FileContext> fileContextForTest(
  1. String name,
  2. String sourceText
)

Creates a temporary file with the given name and sourceText using the test_descriptor package, sets up analysis for that file, and returns a FileContext wrapper around it.

Use this to setup tests for Suggestors: test('My suggestor', () async { var context = await fileContextForTest('foo.dart', 'library foo; // etc'); var patches = MySuggestor().generatePatches(context); expect(patches, ...); });

See also: PackageContextForTest if testing Suggestors that need a fully resolved AST from the analyzer.

Implementation

Future<FileContext> fileContextForTest(String name, String sourceText) async {
  // Use test_descriptor to create the file in a temporary directory
  d.Descriptor descriptor;
  final segments = p.split(name);
  // Last segment should be the file
  descriptor = d.file(segments.last, sourceText);
  // Any preceding segments (if any) are directories
  for (final dir in segments.reversed.skip(1)) {
    descriptor = d.dir(dir, [descriptor]);
  }
  await descriptor.create();

  // Setup analysis for this file
  final path = p.canonicalize(d.path(name));
  final collection = AnalysisContextCollection(includedPaths: [path]);

  return FileContext(path, collection, root: d.sandbox);
}