test_test.dart 14.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7 8 9 10 11 12
// TODO(gspencergoog): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/85160
// Fails with "flutter test --test-randomize-ordering-seed=1000"
@Tags(<String>['no-shuffle'])

13
import 'dart:async';
14
import 'dart:convert';
15

16
import 'package:flutter_tools/src/base/file_system.dart';
17
import 'package:flutter_tools/src/base/io.dart';
18

19 20
import '../src/common.dart';
import 'test_utils.dart';
21 22 23

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

24 25 26
final String automatedTestsDirectory = fileSystem.path.join('..', '..', 'dev', 'automated_tests');
final String missingDependencyDirectory = fileSystem.path.join('..', '..', 'dev', 'missing_dependency_tests');
final String flutterTestDirectory = fileSystem.path.join(automatedTestsDirectory, 'flutter_test');
27
final String integrationTestDirectory = fileSystem.path.join(automatedTestsDirectory, 'integration_test');
28
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', platform.isWindows ? 'flutter.bat' : 'flutter');
29

30 31 32 33
// Running Integration Tests in the Flutter Tester will still exercise the same
// flows specific to Integration Tests.
final List<String> integrationTestExtraArgs = <String>['-d', 'flutter-tester'];

34
void main() {
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
  setUpAll(() async {
    await processManager.run(
      <String>[
        flutterBin,
        'pub',
        'get'
      ],
      workingDirectory: flutterTestDirectory
    );
    await processManager.run(
      <String>[
        flutterBin,
        'pub',
        'get'
      ],
      workingDirectory: missingDependencyDirectory
    );
  });
53

54
  testWithoutContext('flutter test should not have extraneous error messages', () async {
55 56
    return _testFile('trivial_widget', automatedTestsDirectory, flutterTestDirectory, exitCode: isZero);
  });
57

58 59 60 61
  testWithoutContext('integration test should not have extraneous error messages', () async {
    return _testFile('trivial_widget', automatedTestsDirectory, integrationTestDirectory, exitCode: isZero, extraArguments: integrationTestExtraArgs);
  });

62 63 64 65
  testWithoutContext('flutter test set the working directory correctly', () async {
    return _testFile('working_directory', automatedTestsDirectory, flutterTestDirectory, exitCode: isZero);
  });

66
  testWithoutContext('flutter test should report nice errors for exceptions thrown within testWidgets()', () async {
67 68
    return _testFile('exception_handling', automatedTestsDirectory, flutterTestDirectory);
  });
69

70 71 72 73
  testWithoutContext('integration test should report nice errors for exceptions thrown within testWidgets()', () async {
    return _testFile('exception_handling', automatedTestsDirectory, integrationTestDirectory, extraArguments: integrationTestExtraArgs);
  });

74
  testWithoutContext('flutter test should report a nice error when a guarded function was called without await', () async {
75 76
    return _testFile('test_async_utils_guarded', automatedTestsDirectory, flutterTestDirectory);
  });
77

78
  testWithoutContext('flutter test should report a nice error when an async function was called without await', () async {
79 80
    return _testFile('test_async_utils_unguarded', automatedTestsDirectory, flutterTestDirectory);
  });
81

82
  testWithoutContext('flutter test should report a nice error when a Ticker is left running', () async {
83 84
    return _testFile('ticker', automatedTestsDirectory, flutterTestDirectory);
  });
85

86 87
  testWithoutContext('flutter test should report a nice error when a pubspec.yaml is missing a flutter_test dependency', () async {
    final String missingDependencyTests = fileSystem.path.join('..', '..', 'dev', 'missing_dependency_tests');
88 89
    return _testFile('trivial', missingDependencyTests, missingDependencyTests);
  });
90

91
  testWithoutContext('flutter test should report which user-created widget caused the error', () async {
92
    return _testFile('print_user_created_ancestor', automatedTestsDirectory, flutterTestDirectory,
93
        extraArguments: const <String>['--track-widget-creation']);
94
  });
95

96
  testWithoutContext('flutter test should report which user-created widget caused the error - no flag', () async {
97 98 99
    return _testFile('print_user_created_ancestor_no_flag', automatedTestsDirectory, flutterTestDirectory,
       extraArguments: const <String>['--no-track-widget-creation']);
  });
100

101
  testWithoutContext('flutter test should report the correct user-created widget that caused the error', () async {
102 103 104
    return _testFile('print_correct_local_widget', automatedTestsDirectory, flutterTestDirectory,
      extraArguments: const <String>['--track-widget-creation']);
  });
105

106
  testWithoutContext('flutter test should can load assets within its own package', () async {
107 108
    return _testFile('package_assets', automatedTestsDirectory, flutterTestDirectory, exitCode: isZero);
  });
109

110 111 112 113 114
  testWithoutContext('flutter test should support dart defines', () async {
    return _testFile('dart_defines', automatedTestsDirectory, flutterTestDirectory, exitCode: isZero,
      extraArguments: <String>['--dart-define=flutter.test.foo=bar']);
  });

115
  testWithoutContext('flutter test should run a test when its name matches a regexp', () async {
116 117 118 119 120 121 122
    final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory,
      extraArguments: const <String>['--name', 'inc.*de']);
    if (!(result.stdout as String).contains('+1: All tests passed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 0);
  });
123

124
  testWithoutContext('flutter test should run a test when its name contains a string', () async {
125 126 127 128 129 130 131
    final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory,
      extraArguments: const <String>['--plain-name', 'include']);
    if (!(result.stdout as String).contains('+1: All tests passed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 0);
  });
132

133
  testWithoutContext('flutter test should run a test with a given tag', () async {
134 135 136 137 138 139 140 141
    final ProcessResult result = await _runFlutterTest('filtering_tag', automatedTestsDirectory, flutterTestDirectory,
        extraArguments: const <String>['--tags', 'include-tag']);
    if (!(result.stdout as String).contains('+1: All tests passed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 0);
  });

142
  testWithoutContext('flutter test should not run a test with excluded tag', () async {
143 144 145 146 147 148 149 150
    final ProcessResult result = await _runFlutterTest('filtering_tag', automatedTestsDirectory, flutterTestDirectory,
        extraArguments: const <String>['--exclude-tags', 'exclude-tag']);
    if (!(result.stdout as String).contains('+1: All tests passed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 0);
  });

151
  testWithoutContext('flutter test should run all tests when tags are unspecified', () async {
152 153 154 155 156 157 158
    final ProcessResult result = await _runFlutterTest('filtering_tag', automatedTestsDirectory, flutterTestDirectory);
    if (!(result.stdout as String).contains('+1 -1: Some tests failed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 1);
  });

159
  testWithoutContext('flutter test should run a widgetTest with a given tag', () async {
160 161 162 163 164 165 166 167
    final ProcessResult result = await _runFlutterTest('filtering_tag_widget', automatedTestsDirectory, flutterTestDirectory,
        extraArguments: const <String>['--tags', 'include-tag']);
    if (!(result.stdout as String).contains('+1: All tests passed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 0);
  });

168
  testWithoutContext('flutter test should not run a widgetTest with excluded tag', () async {
169 170 171 172 173 174 175 176
    final ProcessResult result = await _runFlutterTest('filtering_tag_widget', automatedTestsDirectory, flutterTestDirectory,
        extraArguments: const <String>['--exclude-tags', 'exclude-tag']);
    if (!(result.stdout as String).contains('+1: All tests passed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 0);
  });

177
  testWithoutContext('flutter test should run all widgetTest when tags are unspecified', () async {
178 179 180 181 182 183 184
    final ProcessResult result = await _runFlutterTest('filtering_tag_widget', automatedTestsDirectory, flutterTestDirectory);
    if (!(result.stdout as String).contains('+1 -1: Some tests failed')) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    expect(result.exitCode, 1);
  });

185
  testWithoutContext('flutter test should test runs to completion', () async {
186 187 188 189
    final ProcessResult result = await _runFlutterTest('trivial', automatedTestsDirectory, flutterTestDirectory,
      extraArguments: const <String>['--verbose']);
    final String stdout = result.stdout as String;
    if ((!stdout.contains('+1: All tests passed')) ||
190
        (!stdout.contains('test 0: Starting flutter_tester process with command')) ||
191 192 193 194 195 196 197 198 199 200 201
        (!stdout.contains('test 0: deleting temporary directory')) ||
        (!stdout.contains('test 0: finished')) ||
        (!stdout.contains('test package returned with exit code 0'))) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    if ((result.stderr as String).isNotEmpty) {
      fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n');
    }
    expect(result.exitCode, 0);
  });

202
  testWithoutContext('flutter test should run all tests inside of a directory with no trailing slash', () async {
203
    final ProcessResult result = await _runFlutterTest(null, automatedTestsDirectory, '$flutterTestDirectory/child_directory',
204 205 206
      extraArguments: const <String>['--verbose']);
    final String stdout = result.stdout as String;
    if ((!stdout.contains('+2: All tests passed')) ||
207
        (!stdout.contains('test 0: Starting flutter_tester process with command')) ||
208 209 210 211 212 213 214 215 216
        (!stdout.contains('test 0: deleting temporary directory')) ||
        (!stdout.contains('test 0: finished')) ||
        (!stdout.contains('test package returned with exit code 0'))) {
      fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
    }
    if ((result.stderr as String).isNotEmpty) {
      fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n');
    }
    expect(result.exitCode, 0);
217
  });
218 219 220 221

  testWithoutContext('flutter gold skips tests where the expectations are missing', () async {
    return _testFile('flutter_gold', automatedTestsDirectory, flutterTestDirectory, exitCode: isZero);
  });
222 223
}

224
Future<void> _testFile(
225 226 227 228 229 230
  String testName,
  String workingDirectory,
  String testDirectory, {
  Matcher exitCode,
  List<String> extraArguments = const <String>[],
}) async {
231
  exitCode ??= isNonZero;
232 233
  final String fullTestExpectation = fileSystem.path.join(testDirectory, '${testName}_expectation.txt');
  final File expectationFile = fileSystem.file(fullTestExpectation);
234
  if (!expectationFile.existsSync()) {
235
    fail('missing expectation file: $expectationFile');
236
  }
237

238 239 240 241 242 243
  final ProcessResult exec = await _runFlutterTest(
    testName,
    workingDirectory,
    testDirectory,
    extraArguments: extraArguments,
  );
244

245
  expect(exec.exitCode, exitCode);
246
  final List<String> output = (exec.stdout as String).split('\n');
247
  if (output.first.startsWith('Waiting for another flutter command to release the startup lock...')) {
248
    output.removeAt(0);
249 250
  }
  if (output.first.startsWith('Running "flutter pub get" in')) {
251
    output.removeAt(0);
252
  }
253 254 255
  // Whether cached artifacts need to be downloaded is dependent on what
  // previous tests have run. Disregard these messages.
  output.removeWhere(RegExp(r'Downloading .*\.\.\.').hasMatch);
256
  output.add('<<stderr>>');
257
  output.addAll((exec.stderr as String).split('\n'));
258
  final List<String> expectations = fileSystem.file(fullTestExpectation).readAsLinesSync();
259 260 261
  bool allowSkip = false;
  int expectationLineNumber = 0;
  int outputLineNumber = 0;
262
  bool haveSeenStdErrMarker = false;
263
  while (expectationLineNumber < expectations.length) {
264 265 266 267 268
    expect(
      output,
      hasLength(greaterThan(outputLineNumber)),
      reason: 'Failure in $testName to compare to $fullTestExpectation',
    );
269
    final String expectationLine = expectations[expectationLineNumber];
270
    String outputLine = output[outputLineNumber];
271 272 273 274 275 276
    if (expectationLine == '<<skip until matching line>>') {
      allowSkip = true;
      expectationLineNumber += 1;
      continue;
    }
    if (allowSkip) {
277
      if (!RegExp(expectationLine).hasMatch(outputLine)) {
278 279 280 281 282
        outputLineNumber += 1;
        continue;
      }
      allowSkip = false;
    }
283 284 285 286
    if (expectationLine == '<<stderr>>') {
      expect(haveSeenStdErrMarker, isFalse);
      haveSeenStdErrMarker = true;
    }
287 288 289 290 291 292 293 294 295 296 297 298
    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;
      }
    }

299
    expect(outputLine, matches(expectationLine), reason: 'Full output:\n- - - -----8<----- - - -\n${output.join("\n")}\n- - - -----8<----- - - -');
300 301 302 303
    expectationLineNumber += 1;
    outputLineNumber += 1;
  }
  expect(allowSkip, isFalse);
304
  if (!haveSeenStdErrMarker) {
305
    expect(exec.stderr, '');
306
  }
307
}
308

309 310 311 312
Future<ProcessResult> _runFlutterTest(
  String testName,
  String workingDirectory,
  String testDirectory, {
313
  List<String> extraArguments = const <String>[],
314 315
}) async {

316 317 318 319
  String testPath;
  if (testName == null) {
    // Test everything in the directory.
    testPath = testDirectory;
320
    final Directory directoryToTest = fileSystem.directory(testPath);
321
    if (!directoryToTest.existsSync()) {
322
      fail('missing test directory: $directoryToTest');
323
    }
324 325
  } else {
    // Test just a specific test file.
326 327
    testPath = fileSystem.path.join(testDirectory, '${testName}_test.dart');
    final File testFile = fileSystem.file(testPath);
328
    if (!testFile.existsSync()) {
329
      fail('missing test file: $testFile');
330
    }
331
  }
332

333 334 335
  final List<String> args = <String>[
    'test',
    '--no-color',
336
    '--no-version-check',
337
    '--no-pub',
338
    ...extraArguments,
339
    testPath,
340
  ];
341

342 343 344 345 346 347 348
  return Process.run(
    flutterBin, // Uses the precompiled flutter tool for faster tests,
    args,
    workingDirectory: workingDirectory,
    stdoutEncoding: utf8,
    stderrEncoding: utf8,
  );
349
}