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

import 'dart:io';

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

import '../analyze.dart';
10
import '../utils.dart';
11 12 13 14
import 'common.dart';

typedef AsyncVoidCallback = Future<void> Function();

15
Future<String> capture(AsyncVoidCallback callback, { bool shouldHaveErrors = false }) async {
16 17 18
  final StringBuffer buffer = StringBuffer();
  final PrintCallback oldPrint = print;
  try {
19
    print = (Object? line) {
20 21
      buffer.writeln(line);
    };
22 23 24 25 26 27
    await callback();
    expect(
      hasError,
      shouldHaveErrors,
      reason: buffer.isEmpty ? '(No output to report.)' : hasError ? 'Unexpected errors:\n$buffer' : 'Unexpected success:\n$buffer',
    );
28 29
  } finally {
    print = oldPrint;
30
    resetErrorStatus();
31
  }
32 33 34 35 36 37
  if (stdout.supportsAnsiEscapes) {
    // Remove ANSI escapes when this test is running on a terminal.
    return buffer.toString().replaceAll(RegExp(r'(\x9B|\x1B\[)[0-?]{1,3}[ -/]*[@-~]'), '');
  } else {
    return buffer.toString();
  }
38 39 40
}

void main() {
41
  final String testRootPath = path.join('test', 'analyze-test-input', 'root');
42 43
  final String dartName = Platform.isWindows ? 'dart.exe' : 'dart';
  final String dartPath = path.canonicalize(path.join('..', '..', 'bin', 'cache', 'dart-sdk', 'bin', dartName));
44

45
  test('analyze.dart - verifyDeprecations', () async {
46
    final String result = await capture(() => verifyDeprecations(testRootPath, minimumMatches: 2), shouldHaveErrors: true);
47
    final String lines = <String>[
48 49 50 51 52 53 54 55 56 57 58 59
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:12: Deprecation notice does not match required pattern.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:18: Deprecation notice should be a grammatically correct sentence and start with a capital letter; see style guide: STYLE_GUIDE_URL',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:25: Deprecation notice should be a grammatically correct sentence and end with a period.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:29: Deprecation notice does not match required pattern.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:32: Deprecation notice does not match required pattern.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:37: Deprecation notice does not match required pattern.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:41: Deprecation notice does not match required pattern.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:48: End of deprecation notice does not match required pattern.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:51: Unexpected deprecation notice indent.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:70: Deprecation notice does not accurately indicate a beta branch version number; please see RELEASES_URL to find the latest beta build version number.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:76: Deprecation notice does not accurately indicate a beta branch version number; please see RELEASES_URL to find the latest beta build version number.',
        '║ test/analyze-test-input/root/packages/foo/deprecation.dart:99: Deprecation notice does not match required pattern. You might have used double quotes (") for the string instead of single quotes (\').',
60 61 62 63 64 65 66 67
      ]
      .map((String line) {
        return line
          .replaceAll('/', Platform.isWindows ? r'\' : '/')
          .replaceAll('STYLE_GUIDE_URL', 'https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo')
          .replaceAll('RELEASES_URL', 'https://flutter.dev/docs/development/tools/sdk/releases');
      })
      .join('\n');
68
    expect(result,
69
      '╔═╡ERROR╞═══════════════════════════════════════════════════════════════════════\n'
70
      '$lines\n'
71 72
      '║ See: https://github.com/flutter/flutter/wiki/Tree-hygiene#handling-breaking-changes\n'
      '╚═══════════════════════════════════════════════════════════════════════════════\n'
73 74 75
    );
  });

76
  test('analyze.dart - verifyGoldenTags', () async {
77
    final List<String> result = (await capture(() => verifyGoldenTags(testRootPath, minimumMatches: 6), shouldHaveErrors: true)).split('\n');
78
    const String noTag = "Files containing golden tests must be tagged using @Tags(<String>['reduced-test-set']) "
79
                         'at the top of the file before import statements.';
80
    const String missingTag = "Files containing golden tests must be tagged with 'reduced-test-set'.";
81 82 83
    final List<String> lines = <String>[
        '║ test/analyze-test-input/root/packages/foo/golden_missing_tag.dart: $missingTag',
        '║ test/analyze-test-input/root/packages/foo/golden_no_tag.dart: $noTag',
84
      ]
85 86 87 88 89 90 91 92
      .map((String line) => line.replaceAll('/', Platform.isWindows ? r'\' : '/'))
      .toList();
    expect(result.length, 4 + lines.length, reason: 'output had unexpected number of lines:\n${result.join('\n')}');
    expect(result[0], '╔═╡ERROR╞═══════════════════════════════════════════════════════════════════════');
    expect(result.getRange(1, result.length - 3).toSet(), lines.toSet());
    expect(result[result.length - 3], '║ See: https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter');
    expect(result[result.length - 2], '╚═══════════════════════════════════════════════════════════════════════════════');
    expect(result[result.length - 1], ''); // trailing newline
93 94
  });

95
  test('analyze.dart - verifyNoMissingLicense', () async {
96
    final String result = await capture(() => verifyNoMissingLicense(testRootPath, checkMinimums: false), shouldHaveErrors: true);
97
    final String file = 'test/analyze-test-input/root/packages/foo/foo.dart'
98
      .replaceAll('/', Platform.isWindows ? r'\' : '/');
Ian Hickson's avatar
Ian Hickson committed
99
    expect(result,
100 101 102 103 104 105 106 107 108
      '╔═╡ERROR╞═══════════════════════════════════════════════════════════════════════\n'
      '║ The following file does not have the right license header for dart files:\n'
      '║   $file\n'
      '║ The expected license header is:\n'
      '║ // Copyright 2014 The Flutter Authors. All rights reserved.\n'
      '║ // Use of this source code is governed by a BSD-style license that can be\n'
      '║ // found in the LICENSE file.\n'
      '║ ...followed by a blank line.\n'
      '╚═══════════════════════════════════════════════════════════════════════════════\n'
Ian Hickson's avatar
Ian Hickson committed
109
    );
110
  });
111 112

  test('analyze.dart - verifyNoTrailingSpaces', () async {
113
    final String result = await capture(() => verifyNoTrailingSpaces(testRootPath, minimumMatches: 2), shouldHaveErrors: true);
114
    final String lines = <String>[
115 116
        '║ test/analyze-test-input/root/packages/foo/spaces.txt:5: trailing U+0020 space character',
        '║ test/analyze-test-input/root/packages/foo/spaces.txt:9: trailing blank line',
117 118 119
      ]
      .map((String line) => line.replaceAll('/', Platform.isWindows ? r'\' : '/'))
      .join('\n');
120
    expect(result,
121
      '╔═╡ERROR╞═══════════════════════════════════════════════════════════════════════\n'
122
      '$lines\n'
123
      '╚═══════════════════════════════════════════════════════════════════════════════\n'
124 125 126 127 128 129
    );
  });

  test('analyze.dart - verifyNoBinaries - positive', () async {
    final String result = await capture(() => verifyNoBinaries(
      testRootPath,
130
      legacyBinaries: <Hash256>{const Hash256(0x39A050CD69434936, 0, 0, 0)},
131
    ), shouldHaveErrors: !Platform.isWindows);
132
    if (!Platform.isWindows) {
133
      expect(result,
134 135 136 137 138 139 140 141 142 143
        '╔═╡ERROR╞═══════════════════════════════════════════════════════════════════════\n'
        '║ test/analyze-test-input/root/packages/foo/serviceaccount.enc:0: file is not valid UTF-8\n'
        '║ All files in this repository must be UTF-8. In particular, images and other binaries\n'
        '║ must not be checked into this repository. This is because we are very sensitive to the\n'
        '║ size of the repository as it is distributed to all our developers. If you have a binary\n'
        '║ to which you need access, you should consider how to fetch it from another repository;\n'
        '║ for example, the "assets-for-api-docs" repository is used for images in API docs.\n'
        '║ To add assets to flutter_tools templates, see the instructions in the wiki:\n'
        '║ https://github.com/flutter/flutter/wiki/Managing-template-image-assets\n'
        '╚═══════════════════════════════════════════════════════════════════════════════\n'
144
      );
145 146 147
    }
  });

148
  test('analyze.dart - verifyInternationalizations - comparison fails', () async {
149
    final String result = await capture(() => verifyInternationalizations(testRootPath, dartPath), shouldHaveErrors: true);
150 151 152 153 154 155 156 157 158 159 160 161 162
    final String genLocalizationsScript = path.join('dev', 'tools', 'localization', 'bin', 'gen_localizations.dart');
    expect(result,
        contains('$dartName $genLocalizationsScript --cupertino'));
    expect(result,
        contains('$dartName $genLocalizationsScript --material'));
    final String generatedFile = path.join(testRootPath, 'packages', 'flutter_localizations',
        'lib', 'src', 'l10n', 'generated_material_localizations.dart');
    expect(result,
        contains('The contents of $generatedFile are different from that produced by gen_localizations.'));
    expect(result,
        contains(r'Did you forget to run gen_localizations.dart after updating a .arb file?'));
  });

163 164 165
  test('analyze.dart - verifyNoBinaries - negative', () async {
    await capture(() => verifyNoBinaries(
      testRootPath,
166
      legacyBinaries: <Hash256>{
167 168
        const Hash256(0xA8100AE6AA1940D0, 0xB663BB31CD466142, 0xEBBDBD5187131B92, 0xD93818987832EB89), // sha256("\xff")
        const Hash256(0x155644D3F13D98BF, 0, 0, 0),
169
      },
170
    ));
171
  });
172 173 174 175 176

  test('analyze.dart - verifyNullInitializedDebugExpensiveFields', () async {
    final String result = await capture(() => verifyNullInitializedDebugExpensiveFields(
      testRootPath,
      minimumMatches: 1,
177
    ), shouldHaveErrors: true);
178 179 180 181

    expect(result, contains('L15'));
    expect(result, isNot(contains('L12')));
  });
182
}