create_api_docs_test.dart 17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2014 The Flutter 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 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:test/test.dart';

import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import '../create_api_docs.dart' as apidocs;
13
import '../dartdoc_checker.dart';
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

void main() {
  group('FlutterInformation', () {
    late FakeProcessManager fakeProcessManager;
    late FakePlatform fakePlatform;
    late MemoryFileSystem memoryFileSystem;
    late apidocs.FlutterInformation flutterInformation;

    void setUpWithEnvironment(Map<String, String> environment) {
      fakePlatform = FakePlatform(environment: environment);
      flutterInformation = apidocs.FlutterInformation(
        filesystem: memoryFileSystem,
        processManager: fakeProcessManager,
        platform: fakePlatform,
      );
      apidocs.FlutterInformation.instance = flutterInformation;
    }

    setUp(() {
      fakeProcessManager = FakeProcessManager.empty();
      memoryFileSystem = MemoryFileSystem();
      setUpWithEnvironment(<String, String>{});
    });

38 39 40 41 42 43 44 45 46 47
    test('getBranchName does not call git if env LUCI_BRANCH provided', () {
      setUpWithEnvironment(
        <String, String>{
          'LUCI_BRANCH': branchName,
        },
      );
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['flutter', '--version', '--machine'],
        stdout: testVersionInfo,
      ));
48 49 50
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'rev-parse', 'HEAD'],
      ));
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
      expect(
        apidocs.FlutterInformation.instance.getBranchName(),
        branchName,
      );
      expect(fakeProcessManager, hasNoRemainingExpectations);
    });

    test('getBranchName calls git if env LUCI_BRANCH not provided', () {
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['flutter', '--version', '--machine'],
        stdout: testVersionInfo,
      ));
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'status', '-b', '--porcelain'],
        stdout: '## $branchName',
      ));
67 68 69
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'rev-parse', 'HEAD'],
      ));
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

      expect(
        apidocs.FlutterInformation.instance.getBranchName(),
        branchName,
      );
      expect(fakeProcessManager, hasNoRemainingExpectations);
    });

    test('getBranchName calls git if env LUCI_BRANCH is empty', () {
      setUpWithEnvironment(
        <String, String>{
          'LUCI_BRANCH': '',
        },
      );
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['flutter', '--version', '--machine'],
        stdout: testVersionInfo,
      ));
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'status', '-b', '--porcelain'],
        stdout: '## $branchName',
      ));
92 93 94
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'rev-parse', 'HEAD'],
      ));
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

      expect(
        apidocs.FlutterInformation.instance.getBranchName(),
        branchName,
      );
      expect(fakeProcessManager, hasNoRemainingExpectations);
    });

    test("runPubProcess doesn't use the pub binary", () {
      final Platform platform = FakePlatform(
        environment: <String, String>{
          'FLUTTER_ROOT': '/flutter',
        },
      );
      final ProcessManager processManager = FakeProcessManager.list(
        <FakeCommand>[
          const FakeCommand(
            command: <String>['/flutter/bin/flutter', 'pub', '--one', '--two'],
          ),
        ],
      );
      apidocs.FlutterInformation.instance =
          apidocs.FlutterInformation(platform: platform, processManager: processManager, filesystem: memoryFileSystem);

      apidocs.runPubProcess(
        arguments: <String>['--one', '--two'],
        processManager: processManager,
        filesystem: memoryFileSystem,
      );

      expect(processManager, hasNoRemainingExpectations);
    });

128
    test('calls out to flutter if FLUTTER_VERSION is not set', () async {
129 130 131 132 133 134 135 136
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['flutter', '--version', '--machine'],
        stdout: testVersionInfo,
      ));
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'status', '-b', '--porcelain'],
        stdout: '## $branchName',
      ));
137 138 139
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'rev-parse', 'HEAD'],
      ));
140 141 142 143 144 145 146 147
      final Map<String, dynamic> info = flutterInformation.getFlutterInformation();
      expect(fakeProcessManager, hasNoRemainingExpectations);
      expect(info['frameworkVersion'], equals(Version.parse('2.5.0')));
    });
    test("doesn't call out to flutter if FLUTTER_VERSION is set", () async {
      setUpWithEnvironment(<String, String>{
        'FLUTTER_VERSION': testVersionInfo,
      });
148 149 150 151
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'status', '-b', '--porcelain'],
        stdout: '## $branchName',
      ));
152 153 154
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'rev-parse', 'HEAD'],
      ));
155 156 157 158 159
      final Map<String, dynamic> info = flutterInformation.getFlutterInformation();
      expect(fakeProcessManager, hasNoRemainingExpectations);
      expect(info['frameworkVersion'], equals(Version.parse('2.5.0')));
    });
    test('getFlutterRoot calls out to flutter if FLUTTER_ROOT is not set', () async {
160 161 162 163 164 165 166 167
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['flutter', '--version', '--machine'],
        stdout: testVersionInfo,
      ));
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'status', '-b', '--porcelain'],
        stdout: '## $branchName',
      ));
168 169 170
      fakeProcessManager.addCommand(const FakeCommand(
        command: <Pattern>['git', 'rev-parse', 'HEAD'],
      ));
171 172 173 174 175 176 177 178 179 180 181 182
      final Directory root = flutterInformation.getFlutterRoot();
      expect(fakeProcessManager, hasNoRemainingExpectations);
      expect(root.path, equals('/home/user/flutter'));
    });
    test("getFlutterRoot doesn't call out to flutter if FLUTTER_ROOT is set", () async {
      setUpWithEnvironment(<String, String>{'FLUTTER_ROOT': '/home/user/flutter'});
      final Directory root = flutterInformation.getFlutterRoot();
      expect(fakeProcessManager, hasNoRemainingExpectations);
      expect(root.path, equals('/home/user/flutter'));
    });
    test('parses version properly', () async {
      fakePlatform.environment['FLUTTER_VERSION'] = testVersionInfo;
183 184 185 186 187 188 189 190 191
      fakeProcessManager.addCommands(<FakeCommand>[
        const FakeCommand(
          command: <Pattern>['git', 'status', '-b', '--porcelain'],
          stdout: '## $branchName',
        ),
        const FakeCommand(
          command: <String>['git', 'rev-parse', 'HEAD'],
        ),
      ]);
192 193 194 195 196 197
      final Map<String, dynamic> info = flutterInformation.getFlutterInformation();
      expect(info['frameworkVersion'], isNotNull);
      expect(info['frameworkVersion'], equals(Version.parse('2.5.0')));
      expect(info['dartSdkVersion'], isNotNull);
      expect(info['dartSdkVersion'], equals(Version.parse('2.14.0-360.0.dev')));
    });
198
    test('the engine realm is read from the engine.realm file', () async {
199 200 201 202 203 204 205 206 207 208
      final Directory flutterHome = memoryFileSystem
          .directory('/home')
          .childDirectory('user')
          .childDirectory('flutter')
          .childDirectory('bin')
          .childDirectory('internal');
      flutterHome.childFile('engine.realm')
        ..createSync(recursive: true)
        ..writeAsStringSync('realm');
      setUpWithEnvironment(<String, String>{'FLUTTER_ROOT': '/home/user/flutter'});
209 210 211 212 213 214 215 216 217 218 219 220 221
      fakeProcessManager.addCommands(<FakeCommand>[
        const FakeCommand(
          command: <Pattern>['/home/user/flutter/bin/flutter', '--version', '--machine'],
          stdout: testVersionInfo,
        ),
        const FakeCommand(
          command: <Pattern>['git', 'status', '-b', '--porcelain'],
          stdout: '## $branchName',
        ),
        const FakeCommand(
          command: <String>['git', 'rev-parse', 'HEAD'],
        ),
      ]);
222
      final Map<String, dynamic> info = flutterInformation.getFlutterInformation();
223
      expect(fakeProcessManager, hasNoRemainingExpectations);
224 225
      expect(info['engineRealm'], equals('realm'));
    });
226
  });
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

  group('DartDocGenerator', () {
    late apidocs.DartdocGenerator generator;
    late MemoryFileSystem fs;
    late FakeProcessManager processManager;
    late Directory publishRoot;

    setUp(() {
      fs = MemoryFileSystem.test();
      publishRoot = fs.directory('/path/to/publish');
      processManager = FakeProcessManager.empty();
      generator = apidocs.DartdocGenerator(
        packageRoot: fs.directory('/path/to/package'),
        publishRoot: publishRoot,
        docsRoot: fs.directory('/path/to/docs'),
        filesystem: fs,
        processManager: processManager,
      );
      final Directory repoRoot = fs.directory('/flutter');
      repoRoot.childDirectory('packages').createSync(recursive: true);
      apidocs.FlutterInformation.instance = apidocs.FlutterInformation(
        filesystem: fs,
        processManager: processManager,
        platform: FakePlatform(environment: <String, String>{
          'FLUTTER_ROOT': repoRoot.path,
        }),
      );
    });

    test('.generateDartDoc() invokes dartdoc with the correct command line arguments', () async {
      processManager.addCommands(<FakeCommand>[
        const FakeCommand(command: <String>['/flutter/bin/flutter', 'pub', 'get']),
        const FakeCommand(
          command: <String>['/flutter/bin/flutter', '--version', '--machine'],
          stdout: testVersionInfo,
        ),
        const FakeCommand(
          command: <Pattern>['git', 'status', '-b', '--porcelain'],
          stdout: '## $branchName',
        ),
        const FakeCommand(
          command: <String>['git', 'rev-parse', 'HEAD'],
        ),
        const FakeCommand(
          command: <String>['/flutter/bin/flutter', 'pub', 'global', 'list'],
        ),
        FakeCommand(
          command: <Pattern>[
            '/flutter/bin/flutter',
            'pub',
            'global',
            'run',
            '--enable-asserts',
            'dartdoc',
            '--output',
            '/path/to/publish/flutter',
            '--allow-tools',
            '--json',
            '--validate-links',
            '--link-to-source-excludes',
            '/flutter/bin/cache',
            '--link-to-source-root',
            '/flutter',
            '--link-to-source-uri-template',
            'https://github.com/flutter/flutter/blob/master/%f%#L%l%',
            '--inject-html',
            '--use-base-href',
            '--header',
            '/path/to/docs/styles.html',
            '--header',
            '/path/to/docs/analytics-header.html',
            '--header',
            '/path/to/docs/survey.html',
            '--header',
            '/path/to/docs/snippets.html',
            '--header',
            '/path/to/docs/opensearch.html',
            '--footer',
            '/path/to/docs/analytics-footer.html',
            '--footer-text',
            '/path/to/package/footer.html',
            '--allow-warnings-in-packages',
            // match package names
            RegExp(r'^(\w+,)+(\w+)$'),
            '--exclude-packages',
            RegExp(r'^(\w+,)+(\w+)$'),
            '--exclude',
            // match dart package URIs
            RegExp(r'^([\w\/:.]+,)+([\w\/:.]+)$'),
            '--favicon',
            '/path/to/docs/favicon.ico',
            '--package-order',
            'flutter,Dart,${apidocs.kPlatformIntegrationPackageName},flutter_test,flutter_driver',
            '--auto-include-dependencies',
          ],
        ),
      ]);

      // This will throw while sanity checking generated files, which is tested independently
      await expectLater(
        () => generator.generateDartdoc(),
        throwsA(
          isA<Exception>().having(
            (Exception e) => e.toString(),
            'message',
            contains(RegExp(r'Missing .* which probably means the documentation failed to build correctly.')),
          ),
        ),
      );

      expect(processManager, hasNoRemainingExpectations);
    });

    test('sanity checks spot check generated files', () async {
      processManager.addCommands(<FakeCommand>[
        const FakeCommand(command: <String>['/flutter/bin/flutter', 'pub', 'get']),
        const FakeCommand(
          command: <String>['/flutter/bin/flutter', '--version', '--machine'],
          stdout: testVersionInfo,
        ),
        const FakeCommand(
          command: <Pattern>['git', 'status', '-b', '--porcelain'],
          stdout: '## $branchName',
        ),
        const FakeCommand(
          command: <String>['git', 'rev-parse', 'HEAD'],
        ),
        const FakeCommand(
          command: <String>['/flutter/bin/flutter', 'pub', 'global', 'list'],
        ),
        FakeCommand(
          command: <Pattern>[
            '/flutter/bin/flutter',
            'pub',
            'global',
            'run',
            '--enable-asserts',
            'dartdoc',
            '--output',
            '/path/to/publish/flutter',
            '--allow-tools',
            '--json',
            '--validate-links',
            '--link-to-source-excludes',
            '/flutter/bin/cache',
            '--link-to-source-root',
            '/flutter',
            '--link-to-source-uri-template',
            'https://github.com/flutter/flutter/blob/master/%f%#L%l%',
            '--inject-html',
            '--use-base-href',
            '--header',
            '/path/to/docs/styles.html',
            '--header',
            '/path/to/docs/analytics-header.html',
            '--header',
            '/path/to/docs/survey.html',
            '--header',
            '/path/to/docs/snippets.html',
            '--header',
            '/path/to/docs/opensearch.html',
            '--footer',
            '/path/to/docs/analytics-footer.html',
            '--footer-text',
            '/path/to/package/footer.html',
            '--allow-warnings-in-packages',
            // match package names
            RegExp(r'^(\w+,)+(\w+)$'),
            '--exclude-packages',
            RegExp(r'^(\w+,)+(\w+)$'),
            '--exclude',
            // match dart package URIs
            RegExp(r'^([\w\/:.]+,)+([\w\/:.]+)$'),
            '--favicon',
            '/path/to/docs/favicon.ico',
            '--package-order',
            'flutter,Dart,${apidocs.kPlatformIntegrationPackageName},flutter_test,flutter_driver',
            '--auto-include-dependencies',
          ],
          onRun: () {
            for (final File canary in generator.canaries) {
              canary.createSync(recursive: true);
            }
            for (final String path in dartdocDirectiveCanaryFiles) {
              publishRoot.childDirectory('flutter').childFile(path).createSync(recursive: true);
            }
            for (final String path in dartdocDirectiveCanaryLibraries) {
              publishRoot.childDirectory('flutter').childDirectory(path).createSync(recursive: true);
            }
            publishRoot.childDirectory('flutter').childFile('index.html').createSync();

            final Directory widgetsDir = publishRoot
                .childDirectory('flutter')
                .childDirectory('widgets')
                ..createSync(recursive: true);
            widgetsDir.childFile('showGeneralDialog.html').writeAsStringSync('''
<pre id="longSnippet1">
  <code class="language-dart">
    import &#39;package:flutter&#47;material.dart&#39;;
  </code>
</pre>
''',
            );
            expect(publishRoot.childDirectory('flutter').existsSync(), isTrue);
            (widgetsDir
              .childDirectory('ModalRoute')
              ..createSync(recursive: true))
              .childFile('barrierColor.html')
              .writeAsStringSync('''
<pre id="sample-code">
  <code class="language-dart">
    class FooClass {
      Color get barrierColor => FooColor();
    }
  </code>
</pre>
''');
            const String queryParams = 'split=1&run=true&sample_id=widgets.Listener.123&sample_channel=master&channel=master';
            widgetsDir.childFile('Listener-class.html').writeAsStringSync('''
<iframe class="snippet-dartpad" src="https://dartpad.dev/embed-flutter.html?$queryParams">
</iframe>
''');
          }
        ),
      ]);

      await generator.generateDartdoc();
    });
  });
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
}

const String branchName = 'stable';
const String testVersionInfo = '''
{
  "frameworkVersion": "2.5.0",
  "channel": "$branchName",
  "repositoryUrl": "git@github.com:flutter/flutter.git",
  "frameworkRevision": "0000000000000000000000000000000000000000",
  "frameworkCommitDate": "2021-07-28 13:03:40 -0700",
  "engineRevision": "0000000000000000000000000000000000000001",
  "dartSdkVersion": "2.14.0 (build 2.14.0-360.0.dev)",
  "flutterRoot": "/home/user/flutter"
}
''';