使用新的测试运行器获取当前脚本路径或当前项目路径

Get current script path or current project path using new test runner

我正在使用新的测试包移植旧的 vm unittest 文件。有些依赖于我的测试文件夹子目录中的输入文件。在我使用 Platform.script 查找此类文件的位置之前。这在使用

时工作正常
$ dart test/my_test.dart

但是使用

$ pub run test

这现在指向一个临时文件夹 (tmp/dart_test_xxxx/runInIsolate.dart)。我无法再找到我的测试输入文件。我不能依赖当前路径,因为我可能 运行 来自不同工作目录的测试。

有没有办法找到 my_test.dart 的位置(或事件项目根路径),从中我可以得出我的文件的位置?

这是 pub run 的当前限制。

当我 运行 遇到这样的需求时,我目前所做的是设置一个环境变量并从测试中读取它们。

我在我的 OS 中设置了它们,并在启动测试之前从其他系统上的 grinder 设置它们。 这也适用于 WebStorm,其中启动配置允许指定环境变量。

这可能是相关的http://dartbug.com/21020

同时我有以下解决方法。如果我直接 运行 或使用 pub 运行 测试,它会给我获取当前测试脚本的目录名,这是一个丑陋的解决方法。如果实现中有任何更改,它肯定会中断,但我非常需要它...

library test_utils.test_script_dir;

import 'dart:io';
import 'package:path/path.dart';

// temp workaround using test package
String get testScriptDir {
  String scriptFilePath = Platform.script.toFilePath();
  print(scriptFilePath);
  if (scriptFilePath.endsWith("runInIsolate.dart")) {

    // Let's look for this line:
    // import "file:///path_to_my_test/test_test.dart" as test;

    String importLineBegin = 'import "file://';
    String importLineEnd = '" as test;';
    int importLineBeginLength = importLineBegin.length;

    String scriptContent = new File.fromUri(Platform.script).readAsStringSync();

    int beginIndex = scriptContent.indexOf(importLineBegin);
    if (beginIndex > -1) {
      int endIndex = scriptContent.indexOf(importLineEnd, beginIndex + importLineBeginLength);
      if (endIndex > -1) {
        scriptFilePath = scriptContent.substring(beginIndex + importLineBegin.length, endIndex);
      }
    }
  }
  return dirname(scriptFilePath);
}