fromPubspec static method

Future<PackageContextForTest> fromPubspec(
  1. String pubspecContents, [
  2. String? dirName
])

Creates a temporary directory named dirName using the test_descriptor package, installs dependencies with dart pub get, sets up an analysis context for the package, and returns a PackageContextForTest wrapper that allows you to add source files to the package and use them in tests.

If dirName is null, a unique name will be generated.

Throws an ArgumentError if it fails to install dependencies.

Implementation

static Future<PackageContextForTest> fromPubspec(
  String pubspecContents, [
  String? dirName,
]) async {
  dirName ??= 'package_${_packageCounter++}';

  await d.dir(dirName, [
    d.file('pubspec.yaml', pubspecContents),
  ]).create();

  final root = p.canonicalize(d.path(dirName));
  final pubGet =
      Process.runSync('dart', ['pub', 'get'], workingDirectory: root);
  if (pubGet.exitCode != 0) {
    printOnFailure('''
PROCESS: dart pub get
WORKING DIR: $root
STDOUT:
${pubGet.stdout}
STDERR:
${pubGet.stderr}
''');
    throw ArgumentError('Failed to install dependencies from given pubspec');
  }
  final collection = AnalysisContextCollection(includedPaths: [root]);
  return PackageContextForTest._(dirName, root, collection);
}