addFile method

Future<FileContext> addFile(
  1. String sourceText, [
  2. String? path
])

Creates a temporary file at the given path (relative to the root of this package) with the given sourceText using the test_descriptor package and returns a FileContext wrapper around it.

If path is null, a unique filename will be generated.

The returned FileContext will use the analysis context for this whole package rather than just this file, which enables testing of Suggestors that require the resolved AST.

See PackageContextForTest for an example.

Implementation

Future<FileContext> addFile(String sourceText, [String? path]) async {
  path ??= 'test_${_fileCounter++}.dart';

  // Use test_descriptor to create the file in a temporary directory
  d.Descriptor descriptor;
  final segments = p.split(path);
  // 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]);
  }
  // Add the root directory.
  descriptor = d.dir(_name, [descriptor]);

  await descriptor.create();
  final canonicalizedPath = p.canonicalize(p.join(d.sandbox, _name, path));
  return FileContext(canonicalizedPath, _collection, root: _root);
}