cache_test.dart 7.2 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.

// @dart = 2.8

import 'dart:io' as io show ProcessSignal;

import 'package:file/file.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
13
import 'package:flutter_tools/src/base/os.dart';
14 15 16
import 'package:flutter_tools/src/base/terminal.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:process/process.dart';
17
import 'package:test/fake.dart';
18 19 20

import '../src/common.dart';
import '../src/context.dart';
21
import '../src/fakes.dart';
22 23 24 25 26 27 28 29
import 'test_utils.dart';

final String dart = fileSystem.path
    .join(getFlutterRoot(), 'bin', platform.isWindows ? 'dart.bat' : 'dart');

void main() {
  group('Cache.lock', () {
    // Windows locking is too flaky for this to work reliably.
30 31 32 33 34 35 36 37 38 39 40 41
    if (platform.isWindows) {
      return;
    }
    testWithoutContext(
        'should log a message to stderr when lock is not acquired', () async {
      final String oldRoot = Cache.flutterRoot;
      final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('cache_test.');
      final BufferLogger logger = BufferLogger(
        terminal: Terminal.test(supportsColor: false, supportsEmoji: false),
        outputPreferences: OutputPreferences(),
      );
      logger.fatalWarnings = true;
42
      Process process;
43 44 45 46 47 48
      try {
        Cache.flutterRoot = tempDir.absolute.path;
        final Cache cache = Cache.test(
          fileSystem: fileSystem,
          processManager: FakeProcessManager.any(),
          logger: logger,
49
        );
50 51 52 53 54 55
        final File cacheFile = fileSystem.file(fileSystem.path
            .join(Cache.flutterRoot, 'bin', 'cache', 'lockfile'))
          ..createSync(recursive: true);
        final File script = fileSystem.file(fileSystem.path
            .join(Cache.flutterRoot, 'bin', 'cache', 'test_lock.dart'));
        script.writeAsStringSync(r'''
56 57 58 59
import 'dart:async';
import 'dart:io';

Future<void> main(List<String> args) async {
60 61 62 63 64 65 66 67 68 69
  File file = File(args[0]);
  final RandomAccessFile lock = file.openSync(mode: FileMode.write);
  while (true) {
    try {
      lock.lockSync();
      break;
    } on FileSystemException {}
  }
  await Future<void>.delayed(const Duration(seconds: 1));
  exit(0);
70 71
}
''');
72 73 74
        // Locks are per-process, so we have to launch a separate process to
        // test out cache locking.
        process = await const LocalProcessManager().start(
75 76
          <String>[dart, script.absolute.path, cacheFile.absolute.path],
        );
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        // Wait for the script to lock the test cache file before checking to
        // see that the cache is unable to.
        bool locked = false;
        while (!locked) {
          // Give the script a chance to try for the lock much more often.
          await Future<void>.delayed(const Duration(milliseconds: 100));
          final RandomAccessFile lock = cacheFile.openSync(mode: FileMode.write);
          try {
            // If we can lock it, unlock immediately to give the script a
            // chance.
            lock.lockSync();
            lock.unlockSync();
          } on FileSystemException {
            // If we can't lock it, then the child script succeeded in locking
            // it, and we can now test.
            locked = true;
            break;
          }
        }
        // Finally, test that the cache cannot lock a locked file. This should
        // print a message if it can't lock the file.
98 99
        await cache.lock();
      } finally {
100 101
        // Just to keep from leaving the process hanging around.
        process?.kill(io.ProcessSignal.sighup);
102 103 104 105 106 107 108 109
        tryToDelete(tempDir);
        Cache.flutterRoot = oldRoot;
      }
      expect(logger.statusText, isEmpty);
      expect(logger.errorText, isEmpty);
      expect(logger.warningText,
          equals('Waiting for another flutter command to release the startup lock...\n'));
      expect(logger.hadErrorOutput, isFalse);
110 111
      // Should still be false, since the particular "Waiting..." message above
      // aims to avoid triggering failure as a fatal warning.
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
      expect(logger.hadWarningOutput, isFalse);
    });
    testWithoutContext(
        'should log a warning message for unknown version ', () async {
      final String oldRoot = Cache.flutterRoot;
      final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('cache_test.');
      final BufferLogger logger = BufferLogger(
        terminal: Terminal.test(supportsColor: false, supportsEmoji: false),
        outputPreferences: OutputPreferences(),
      );
      logger.fatalWarnings = true;
      try {
        Cache.flutterRoot = tempDir.absolute.path;
        final Cache cache = Cache.test(
          fileSystem: fileSystem,
          processManager: FakeProcessManager.any(),
          logger: logger,
        );
        final FakeVersionlessArtifact artifact = FakeVersionlessArtifact(cache);
        cache.registerArtifact(artifact);
        await artifact.update(FakeArtifactUpdater(), logger, fileSystem, FakeOperatingSystemUtils());
      } finally {
        tryToDelete(tempDir);
        Cache.flutterRoot = oldRoot;
      }
      expect(logger.statusText, isEmpty);
      expect(logger.warningText, equals('No known version for the artifact name "fake". '
        'Flutter can continue, but the artifact may be re-downloaded on '
        'subsequent invocations until the problem is resolved.\n'));
      expect(logger.hadErrorOutput, isFalse);
      expect(logger.hadWarningOutput, isTrue);
    });
144
  });
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

  testWithoutContext('Dart SDK target arch matches host arch', () async {
    if (platform.isWindows) {
      return;
    }
    final ProcessResult dartResult = await const LocalProcessManager().run(
      <String>[dart, '--version'],
    );
    // Parse 'arch' out of a string like '... "os_arch"\n'.
    final String dartTargetArch = (dartResult.stdout as String)
      .trim().split(' ').last.replaceAll('"', '').split('_')[1];
    final ProcessResult unameResult = await const LocalProcessManager().run(
      <String>['uname', '-m'],
    );
    final String unameArch = (unameResult.stdout as String)
      .trim().replaceAll('aarch64', 'arm64')
             .replaceAll('x86_64', 'x64');
    expect(dartTargetArch, equals(unameArch));
  });
164
}
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

class FakeArtifactUpdater extends Fake implements ArtifactUpdater {
  void Function(String, Uri, Directory) onDownloadZipArchive;
  void Function(String, Uri, Directory) onDownloadZipTarball;

  @override
  Future<void> downloadZippedTarball(String message, Uri url, Directory location) async {
    onDownloadZipTarball?.call(message, url, location);
  }

  @override
  Future<void> downloadZipArchive(String message, Uri url, Directory location) async {
    onDownloadZipArchive?.call(message, url, location);
  }

  @override
  void removeDownloadedFiles() { }
}

class FakeVersionlessArtifact extends CachedArtifact {
  FakeVersionlessArtifact(Cache cache) : super(
    'fake',
    cache,
    DevelopmentArtifact.universal,
  );

  @override
  String get version => null;

  @override
  Future<void> updateInner(ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils) async { }
}