test_test.dart 11 KB
Newer Older
1 2 3 4 5
// Copyright 2015 The Chromium 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:async';
6
import 'dart:io' as io;
7

8
import 'package:flutter_tools/src/base/file_system.dart';
9
import 'package:flutter_tools/src/base/io.dart';
10 11 12
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/dart/sdk.dart';

13 14
import '../../src/common.dart';
import '../../src/context.dart';
15 16 17

// This test depends on some files in ///dev/automated_tests/flutter_test/*

18
Future<void> _testExclusionLock;
19

20
void main() {
21
  group('flutter test should', () {
22

23 24
    final String automatedTestsDirectory = fs.path.join('..', '..', 'dev', 'automated_tests');
    final String flutterTestDirectory = fs.path.join(automatedTestsDirectory, 'flutter_test');
25

26 27 28
    testUsingContext('not have extraneous error messages', () async {
      Cache.flutterRoot = '../..';
      return _testFile('trivial_widget', automatedTestsDirectory, flutterTestDirectory, exitCode: isZero);
29
    }, skip: io.Platform.isLinux); // Flutter on Linux sometimes has problems with font resolution (#7224)
30

31
    testUsingContext('report nice errors for exceptions thrown within testWidgets()', () async {
32 33
      Cache.flutterRoot = '../..';
      return _testFile('exception_handling', automatedTestsDirectory, flutterTestDirectory);
34
    }, skip: io.Platform.isWindows); // TODO(chunhtai): Dart on Windows has trouble with unicode characters in output (#35425).
35

36
    testUsingContext('report a nice error when a guarded function was called without await', () async {
37
      Cache.flutterRoot = '../..';
38
      return _testFile('test_async_utils_guarded', automatedTestsDirectory, flutterTestDirectory);
39
    }, skip: io.Platform.isWindows); // TODO(chunhtai): Dart on Windows has trouble with unicode characters in output (#35425).
40

41
    testUsingContext('report a nice error when an async function was called without await', () async {
42
      Cache.flutterRoot = '../..';
43
      return _testFile('test_async_utils_unguarded', automatedTestsDirectory, flutterTestDirectory);
44
    }, skip: io.Platform.isWindows); // TODO(chunhtai): Dart on Windows has trouble with unicode characters in output (#35425).
45

46 47 48
    testUsingContext('report a nice error when a Ticker is left running', () async {
      Cache.flutterRoot = '../..';
      return _testFile('ticker', automatedTestsDirectory, flutterTestDirectory);
49
    }, skip: io.Platform.isWindows); // TODO(chunhtai): Dart on Windows has trouble with unicode characters in output (#35425).
50

51
    testUsingContext('report a nice error when a pubspec.yaml is missing a flutter_test dependency', () async {
52
      final String missingDependencyTests = fs.path.join('..', '..', 'dev', 'missing_dependency_tests');
53
      Cache.flutterRoot = '../..';
54
      return _testFile('trivial', missingDependencyTests, missingDependencyTests);
55 56 57 58 59 60 61 62 63 64 65 66
    }, skip: io.Platform.isWindows); // TODO(chunhtai): Dart on Windows has trouble with unicode characters in output (#35425).

    testUsingContext('report which user created widget caused the error', () async {
      Cache.flutterRoot = '../..';
      return _testFile('print_user_created_ancestor', automatedTestsDirectory, flutterTestDirectory,
          extraArguments: const <String>['--track-widget-creation']);
    }, skip: io.Platform.isWindows); // TODO(chunhtai): Dart on Windows has trouble with unicode characters in output (#35425).

    testUsingContext('report which user created widget caused the error - no flag', () async {
      Cache.flutterRoot = '../..';
      return _testFile('print_user_created_ancestor_no_flag', automatedTestsDirectory, flutterTestDirectory);
    }, skip: io.Platform.isWindows); // TODO(chunhtai): Dart on Windows has trouble with unicode characters in output (#35425).
67

68 69 70 71 72
    testUsingContext('can load assets within its own package', () async {
      Cache.flutterRoot = '../..';
      return _testFile('package_assets', automatedTestsDirectory, flutterTestDirectory, exitCode: isZero);
    }, skip: io.Platform.isWindows);

73 74 75
    testUsingContext('run a test when its name matches a regexp', () async {
      Cache.flutterRoot = '../..';
      final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory,
76
        extraArguments: const <String>['--name', 'inc.*de']);
77
      if (!result.stdout.contains('+1: All tests passed')) {
78
        fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
79
      }
80 81 82 83 84 85
      expect(result.exitCode, 0);
    });

    testUsingContext('run a test when its name contains a string', () async {
      Cache.flutterRoot = '../..';
      final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory,
86
        extraArguments: const <String>['--plain-name', 'include']);
87
      if (!result.stdout.contains('+1: All tests passed')) {
88
        fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
89
      }
90 91 92 93 94 95
      expect(result.exitCode, 0);
    });

    testUsingContext('test runs to completion', () async {
      Cache.flutterRoot = '../..';
      final ProcessResult result = await _runFlutterTest('trivial', automatedTestsDirectory, flutterTestDirectory,
96
        extraArguments: const <String>['--verbose']);
97 98 99 100
      if ((!result.stdout.contains('+1: All tests passed')) ||
          (!result.stdout.contains('test 0: starting shell process')) ||
          (!result.stdout.contains('test 0: deleting temporary directory')) ||
          (!result.stdout.contains('test 0: finished')) ||
101
          (!result.stdout.contains('test package returned with exit code 0'))) {
102
        fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
103 104
      }
      if (result.stderr.isNotEmpty) {
105
        fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n');
106
      }
107 108 109
      expect(result.exitCode, 0);
    });

110 111 112 113 114 115 116 117
    testUsingContext('run all tests inside of a directory with no trailing slash', () async {
      Cache.flutterRoot = '../..';
      final ProcessResult result = await _runFlutterTest(null, automatedTestsDirectory, flutterTestDirectory + '/child_directory',
        extraArguments: const <String>['--verbose']);
      if ((!result.stdout.contains('+2: All tests passed')) ||
          (!result.stdout.contains('test 0: starting shell process')) ||
          (!result.stdout.contains('test 0: deleting temporary directory')) ||
          (!result.stdout.contains('test 0: finished')) ||
118
          (!result.stdout.contains('test package returned with exit code 0'))) {
119
        fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
120 121
      }
      if (result.stderr.isNotEmpty) {
122
        fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n');
123
      }
124 125 126
      expect(result.exitCode, 0);
    });

127
  });
128 129
}

130 131 132 133 134 135 136
Future<void> _testFile(
    String testName,
    String workingDirectory,
    String testDirectory, {
      Matcher exitCode,
      List<String> extraArguments = const <String>[],
    }) async {
137
  exitCode ??= isNonZero;
138
  final String fullTestExpectation = fs.path.join(testDirectory, '${testName}_expectation.txt');
139
  final File expectationFile = fs.file(fullTestExpectation);
140
  if (!expectationFile.existsSync()) {
141
    fail('missing expectation file: $expectationFile');
142
  }
143

144
  while (_testExclusionLock != null) {
145
    await _testExclusionLock;
146
  }
147

148 149 150 151 152 153
  final ProcessResult exec = await _runFlutterTest(
    testName,
    workingDirectory,
    testDirectory,
    extraArguments: extraArguments,
  );
154

155
  expect(exec.exitCode, exitCode);
156
  final List<String> output = exec.stdout.split('\n');
157
  if (output.first == 'Waiting for another flutter command to release the startup lock...') {
158
    output.removeAt(0);
159 160
  }
  if (output.first.startsWith('Running "flutter pub get" in')) {
161
    output.removeAt(0);
162
  }
163 164
  output.add('<<stderr>>');
  output.addAll(exec.stderr.split('\n'));
165
  final List<String> expectations = fs.file(fullTestExpectation).readAsLinesSync();
166 167 168
  bool allowSkip = false;
  int expectationLineNumber = 0;
  int outputLineNumber = 0;
169
  bool haveSeenStdErrMarker = false;
170
  while (expectationLineNumber < expectations.length) {
171 172 173 174 175
    expect(
      output,
      hasLength(greaterThan(outputLineNumber)),
      reason: 'Failure in $testName to compare to $fullTestExpectation',
    );
176
    final String expectationLine = expectations[expectationLineNumber];
177
    String outputLine = output[outputLineNumber];
178 179 180 181 182 183
    if (expectationLine == '<<skip until matching line>>') {
      allowSkip = true;
      expectationLineNumber += 1;
      continue;
    }
    if (allowSkip) {
184
      if (!RegExp(expectationLine).hasMatch(outputLine)) {
185 186 187 188 189
        outputLineNumber += 1;
        continue;
      }
      allowSkip = false;
    }
190 191 192 193
    if (expectationLine == '<<stderr>>') {
      expect(haveSeenStdErrMarker, isFalse);
      haveSeenStdErrMarker = true;
    }
194 195 196 197 198 199 200 201 202 203 204 205
    if (!RegExp(expectationLine).hasMatch(outputLine) && outputLineNumber + 1 < output.length) {
      // Check if the RegExp can match the next two lines in the output so
      // that it is possible to write expectations that still hold even if a
      // line is wrapped slightly differently due to for example a file name
      // being longer on one platform than another.
      final String mergedLines = '$outputLine\n${output[outputLineNumber+1]}';
      if (RegExp(expectationLine).hasMatch(mergedLines)) {
        outputLineNumber += 1;
        outputLine = mergedLines;
      }
    }

206
    expect(outputLine, matches(expectationLine), reason: 'Full output:\n- - - -----8<----- - - -\n${output.join("\n")}\n- - - -----8<----- - - -');
207 208 209 210
    expectationLineNumber += 1;
    outputLineNumber += 1;
  }
  expect(allowSkip, isFalse);
211
  if (!haveSeenStdErrMarker) {
212
    expect(exec.stderr, '');
213
  }
214
}
215

216 217 218 219
Future<ProcessResult> _runFlutterTest(
  String testName,
  String workingDirectory,
  String testDirectory, {
220
  List<String> extraArguments = const <String>[],
221 222
}) async {

223 224 225 226 227
  String testPath;
  if (testName == null) {
    // Test everything in the directory.
    testPath = testDirectory;
    final Directory directoryToTest = fs.directory(testPath);
228
    if (!directoryToTest.existsSync()) {
229
      fail('missing test directory: $directoryToTest');
230
    }
231 232
  } else {
    // Test just a specific test file.
233
    testPath = fs.path.join(testDirectory, '${testName}_test.dart');
234
    final File testFile = fs.file(testPath);
235
    if (!testFile.existsSync()) {
236
      fail('missing test file: $testFile');
237
    }
238
  }
239

240 241 242 243 244
  final List<String> args = <String>[
    ...dartVmFlags,
    fs.path.absolute(fs.path.join('bin', 'flutter_tools.dart')),
    'test',
    '--no-color',
245
    ...extraArguments,
246
    testPath,
247
  ];
248

249
  while (_testExclusionLock != null) {
250
    await _testExclusionLock;
251
  }
252

253
  final Completer<void> testExclusionCompleter = Completer<void>();
254 255 256 257 258 259 260 261 262 263 264 265
  _testExclusionLock = testExclusionCompleter.future;
  try {
    return await Process.run(
      fs.path.join(dartSdkPath, 'bin', 'dart'),
      args,
      workingDirectory: workingDirectory,
    );
  } finally {
    _testExclusionLock = null;
    testExclusionCompleter.complete();
  }
}