gradle_errors_test.dart 26.3 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
import 'package:file/memory.dart';
8
import 'package:file_testing/file_testing.dart';
9
import 'package:flutter_tools/src/android/gradle_errors.dart';
10
import 'package:flutter_tools/src/android/gradle_utils.dart';
11
import 'package:flutter_tools/src/base/file_system.dart';
12 13
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
14 15 16 17 18 19 20 21
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';

import '../../src/common.dart';
import '../../src/context.dart';

void main() {
  group('gradleErrors', () {
22
    testWithoutContext('list of errors', () {
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
      // If you added a new Gradle error, please update this test.
      expect(gradleErrors,
        equals(<GradleHandledError>[
          licenseNotAcceptedHandler,
          networkErrorHandler,
          permissionDeniedErrorHandler,
          flavorUndefinedHandler,
          r8FailureHandler,
          androidXFailureHandler,
        ])
      );
    });
  });

  group('network errors', () {
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    testUsingContext('retries and deletes zip if gradle fails to unzip', () async {
      globals.fs.file('foo/.gradle/fizz.zip').createSync(recursive: true);
      const String errorMessage = r'''
Exception in thread "main" java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.(ZipFile.java:225)
at java.util.zip.ZipFile.(ZipFile.java:155)
at java.util.zip.ZipFile.(ZipFile.java:169)
at org.gradle.wrapper.Install.unzip(Install.java:214)
at org.gradle.wrapper.Install.access$600(Install.java:27)
at org.gradle.wrapper.Install$1.call(Install.java:74)
at org.gradle.wrapper.Install$1.call(Install.java:48)
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:48)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
[!] Gradle threw an error while trying to update itself. Retrying the update...
Exception in thread "main" java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.(ZipFile.java:225)
at java.util.zip.ZipFile.(ZipFile.java:155)
at java.util.zip.ZipFile.(ZipFile.java:169)
at org.gradle.wrapper.Install.unzip(Install.java:214)
at org.gradle.wrapper.Install.access$600(Install.java:27)
at org.gradle.wrapper.Install$1.call(Install.java:74)
at org.gradle.wrapper.Install$1.call(Install.java:48)
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:48)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
''';

      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));
      expect(globals.fs.file('foo/.gradle/fizz.zip'), isNot(exists));
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
      Platform: () => FakePlatform(environment: <String, String>{'HOME': 'foo/'}),
    });

79
    testUsingContext('retries if gradle fails while downloading', () async {
80
      const String errorMessage = r'''
81 82 83 84 85 86
Exception in thread "main" java.io.FileNotFoundException: https://downloads.gradle.org/distributions/gradle-4.1.1-all.zip
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1872)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
at org.gradle.wrapper.Download.download(Download.java:44)
87 88
at org.gradle.wrapper.Install$1.call(Install.java:61)
at org.gradle.wrapper.Install$1.call(Install.java:48)
89 90 91 92 93
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:48)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''';

94
      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
95 96
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));

97
      expect(testLogger.errorText,
98
        contains(
99 100
          'Gradle threw an error while downloading artifacts from the network. '
          'Retrying to download...'
101 102
        )
      );
103 104 105
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
106 107
    });

108
    testUsingContext('retries if gradle fails downloading with proxy error', () async {
109
      const String errorMessage = r'''
110 111 112 113 114 115 116 117
Exception in thread "main" java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"
at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:2124)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:183)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1546)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
at org.gradle.wrapper.Download.download(Download.java:44)
118 119
at org.gradle.wrapper.Install$1.call(Install.java:61)
at org.gradle.wrapper.Install$1.call(Install.java:48)
120 121 122 123 124
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:48)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''';

125
      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
126 127
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));

128
      expect(testLogger.errorText,
129
        contains(
130 131
          'Gradle threw an error while downloading artifacts from the network. '
          'Retrying to download...'
132 133
        )
      );
134 135 136
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
137 138
    });

139
    testUsingContext('retries if gradle times out waiting for exclusive access to zip', () async {
140 141 142 143 144 145 146
      const String errorMessage = '''
Exception in thread "main" java.lang.RuntimeException: Timeout of 120000 reached waiting for exclusive access to file: /User/documents/gradle-5.6.2-all.zip
	at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:61)
	at org.gradle.wrapper.Install.createDist(Install.java:48)
	at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
	at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''';

147
      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
148 149
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));

150
      expect(testLogger.errorText,
151
        contains(
152 153
          'Gradle threw an error while downloading artifacts from the network. '
          'Retrying to download...'
154 155
        )
      );
156 157 158
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
159 160
    });

161
    testUsingContext('retries if remote host closes connection', () async {
162
      const String errorMessage = r'''
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
Downloading https://services.gradle.org/distributions/gradle-5.6.2-all.zip
Exception in thread "main" javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:994)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
	at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
	at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
	at sun.net.www.protocol.http.HttpURLConnection.followRedirect0(HttpURLConnection.java:2729)
	at sun.net.www.protocol.http.HttpURLConnection.followRedirect(HttpURLConnection.java:2641)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1824)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
	at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
	at org.gradle.wrapper.Download.download(Download.java:44)
178 179
	at org.gradle.wrapper.Install$1.call(Install.java:61)
	at org.gradle.wrapper.Install$1.call(Install.java:48)
180 181 182 183 184
	at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
	at org.gradle.wrapper.Install.createDist(Install.java:48)
	at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
	at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''';

185
      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
186 187
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));

188
      expect(testLogger.errorText,
189
        contains(
190 191
          'Gradle threw an error while downloading artifacts from the network. '
          'Retrying to download...'
192 193
        )
      );
194 195 196
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
197 198
    });

199
    testUsingContext('retries if file opening fails', () async {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
      const String errorMessage = r'''
Downloading https://services.gradle.org/distributions/gradle-3.5.0-all.zip
Exception in thread "main" java.io.FileNotFoundException: https://downloads.gradle-dn.com/distributions/gradle-3.5.0-all.zip
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1890)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
	at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
	at org.gradle.wrapper.Download.download(Download.java:44)
	at org.gradle.wrapper.Install$1.call(Install.java:61)
	at org.gradle.wrapper.Install$1.call(Install.java:48)
	at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
	at org.gradle.wrapper.Install.createDist(Install.java:48)
	at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
	at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''';

215
      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
216 217
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));

218
      expect(testLogger.errorText,
219
        contains(
220 221
          'Gradle threw an error while downloading artifacts from the network. '
          'Retrying to download...'
222 223
        )
      );
224 225 226
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
227 228
    });

229
    testUsingContext('retries if the connection is reset', () async {
230
      const String errorMessage = r'''
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
Downloading https://services.gradle.org/distributions/gradle-5.6.2-all.zip
Exception in thread "main" java.net.SocketException: Connection reset
	at java.net.SocketInputStream.read(SocketInputStream.java:210)
	at java.net.SocketInputStream.read(SocketInputStream.java:141)
	at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
	at sun.security.ssl.InputRecord.readV3Record(InputRecord.java:593)
	at sun.security.ssl.InputRecord.read(InputRecord.java:532)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
	at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
	at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
	at org.gradle.wrapper.Download.downloadInternal(Download.java:58)
	at org.gradle.wrapper.Download.download(Download.java:44)
249 250
	at org.gradle.wrapper.Install$1.call(Install.java:61)
	at org.gradle.wrapper.Install$1.call(Install.java:48)
251 252 253 254 255
	at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
	at org.gradle.wrapper.Install.createDist(Install.java:48)
	at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
	at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)''';

256
      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
257 258
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));

259
      expect(testLogger.errorText,
260
        contains(
261 262 263 264
          'Gradle threw an error while downloading artifacts from the network. '
          'Retrying to download...'
        )
      );
265 266 267
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    });

    testUsingContext('retries if Gradle could not get a resource', () async {
      const String errorMessage = '''
A problem occurred configuring root project 'android'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve net.sf.proguard:proguard-gradle:6.0.3.
     Required by:
         project : > com.android.tools.build:gradle:3.3.0
      > Could not resolve net.sf.proguard:proguard-gradle:6.0.3.
         > Could not parse POM https://jcenter.bintray.com/net/sf/proguard/proguard-gradle/6.0.3/proguard-gradle-6.0.3.pom
            > Could not resolve net.sf.proguard:proguard-parent:6.0.3.
               > Could not resolve net.sf.proguard:proguard-parent:6.0.3.
                  > Could not get resource 'https://jcenter.bintray.com/net/sf/proguard/proguard-parent/6.0.3/proguard-parent-6.0.3.pom'.
                     > Could not GET 'https://jcenter.bintray.com/net/sf/proguard/proguard-parent/6.0.3/proguard-parent-6.0.3.pom'. Received status code 504 from server: Gateway Time-out''';

284
      expect(formatTestErrorMessage(errorMessage, networkErrorHandler), isTrue);
285 286 287 288 289 290
      expect(await networkErrorHandler.handler(), equals(GradleBuildStatus.retry));

      expect(testLogger.errorText,
        contains(
          'Gradle threw an error while downloading artifacts from the network. '
          'Retrying to download...'
291 292
        )
      );
293 294 295
    }, overrides: <Type, Generator>{
      FileSystem: () => MemoryFileSystem.test(),
      ProcessManager: () => FakeProcessManager.any(),
296 297 298 299 300 301 302 303 304
    });
  });

  group('permission errors', () {
    testUsingContext('throws toolExit if gradle is missing execute permissions', () async {
      const String errorMessage = '''
Permission denied
Command: /home/android/gradlew assembleRelease
''';
305
      expect(formatTestErrorMessage(errorMessage, permissionDeniedErrorHandler), isTrue);
306 307 308
      expect(await permissionDeniedErrorHandler.handler(), equals(GradleBuildStatus.exit));

      expect(
309
        testLogger.statusText,
310
        contains('Gradle does not have execution permission.'),
311 312
      );
      expect(
313
        testLogger.statusText,
314 315 316 317 318 319 320 321 322
        contains(
          'You should change the ownership of the project directory to your user, '
          'or move the project to a directory with execute permissions.'
        )
      );
    });
  });

  group('AndroidX', () {
323
    final TestUsage testUsage = TestUsage();
324

325
    testWithoutContext('pattern', () {
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
      expect(androidXFailureHandler.test(
        'AAPT: error: resource android:attr/fontVariationSettings not found.'
      ), isTrue);

      expect(androidXFailureHandler.test(
        'AAPT: error: resource android:attr/ttcIndex not found.'
      ), isTrue);

      expect(androidXFailureHandler.test(
        'error: package android.support.annotation does not exist'
      ), isTrue);

      expect(androidXFailureHandler.test(
        'import android.support.annotation.NonNull;'
      ), isTrue);

      expect(androidXFailureHandler.test(
        'import androidx.annotation.NonNull;'
      ), isTrue);

      expect(androidXFailureHandler.test(
        'Daemon:  AAPT2 aapt2-3.2.1-4818971-linux Daemon #0'
      ), isTrue);
    });

    testUsingContext('handler - no plugins', () async {
      final GradleBuildStatus status = await androidXFailureHandler
353
        .handler(line: '', project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory));
354

355 356 357 358 359 360 361 362 363 364
      expect(testUsage.events, contains(
        const TestUsageEvent(
          'build',
          'unspecified',
          label: 'gradle-android-x-failure',
          parameters: <String, String>{
            'cd43': 'app-not-using-plugins',
          },
        ),
      ));
365 366 367

      expect(status, equals(GradleBuildStatus.exit));
    }, overrides: <Type, Generator>{
368
      FileSystem: () => MemoryFileSystem.test(),
369
      ProcessManager: () => FakeProcessManager.any(),
370
      Usage: () => testUsage,
371 372 373
    });

    testUsingContext('handler - plugins and no AndroidX', () async {
374
      globals.fs.file('.flutter-plugins').createSync(recursive: true);
375 376 377 378

      final GradleBuildStatus status = await androidXFailureHandler
        .handler(
          line: '',
379
          project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
380 381 382
          usesAndroidX: false,
        );

383
      expect(testLogger.statusText,
384 385
        contains(
          'AndroidX incompatibilities may have caused this build to fail. '
386
          'Please migrate your app to AndroidX. See https://goo.gl/CP92wY .'
387 388
        )
      );
389 390 391 392 393 394 395 396 397 398 399

      expect(testUsage.events, contains(
        const TestUsageEvent(
          'build',
          'unspecified',
          label: 'gradle-android-x-failure',
          parameters: <String, String>{
            'cd43': 'app-not-using-androidx',
          },
        ),
      ));
400 401 402

      expect(status, equals(GradleBuildStatus.exit));
    }, overrides: <Type, Generator>{
403
      FileSystem: () => MemoryFileSystem.test(),
404
      ProcessManager: () => FakeProcessManager.any(),
405
      Usage: () => testUsage,
406 407 408
    });

    testUsingContext('handler - plugins, AndroidX, and AAR', () async {
409
      globals.fs.file('.flutter-plugins').createSync(recursive: true);
410 411 412

      final GradleBuildStatus status = await androidXFailureHandler.handler(
        line: '',
413
        project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
414 415 416 417
        usesAndroidX: true,
        shouldBuildPluginAsAar: true,
      );

418 419 420 421 422 423 424 425 426 427
      expect(testUsage.events, contains(
        const TestUsageEvent(
          'build',
          'unspecified',
          label: 'gradle-android-x-failure',
          parameters: <String, String>{
            'cd43': 'using-jetifier',
          },
        ),
      ));
428 429 430

      expect(status, equals(GradleBuildStatus.exit));
    }, overrides: <Type, Generator>{
431
      FileSystem: () => MemoryFileSystem.test(),
432
      ProcessManager: () => FakeProcessManager.any(),
433
      Usage: () => testUsage,
434 435 436
    });

    testUsingContext('handler - plugins, AndroidX, and no AAR', () async {
437
      globals.fs.file('.flutter-plugins').createSync(recursive: true);
438 439 440

      final GradleBuildStatus status = await androidXFailureHandler.handler(
        line: '',
441
        project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
442 443 444 445
        usesAndroidX: true,
        shouldBuildPluginAsAar: false,
      );

446
      expect(testLogger.statusText,
447
        contains(
448 449
          'The build failed likely due to AndroidX incompatibilities in a plugin. '
          'The tool is about to try using Jetifier to solve the incompatibility.'
450 451
        )
      );
452 453 454 455 456 457 458 459 460 461 462

      expect(testUsage.events, contains(
        const TestUsageEvent(
          'build',
          'unspecified',
          label: 'gradle-android-x-failure',
          parameters: <String, String>{
            'cd43': 'not-using-jetifier',
          },
        ),
      ));
463 464
      expect(status, equals(GradleBuildStatus.retryWithAarPlugins));
    }, overrides: <Type, Generator>{
465
      FileSystem: () => MemoryFileSystem.test(),
466
      ProcessManager: () => FakeProcessManager.any(),
467
      Usage: () => testUsage,
468 469 470 471 472 473 474 475 476
    });
  });

  group('permission errors', () {
    testUsingContext('pattern', () async {
      const String errorMessage = '''
Permission denied
Command: /home/android/gradlew assembleRelease
''';
477
      expect(formatTestErrorMessage(errorMessage, permissionDeniedErrorHandler), isTrue);
478 479 480 481 482 483
    });

    testUsingContext('handler', () async {
      expect(await permissionDeniedErrorHandler.handler(), equals(GradleBuildStatus.exit));

      expect(
484
        testLogger.statusText,
485
        contains('Gradle does not have execution permission.'),
486 487
      );
      expect(
488
        testLogger.statusText,
489 490 491 492 493 494 495 496 497
        contains(
          'You should change the ownership of the project directory to your user, '
          'or move the project to a directory with execute permissions.'
        )
      );
    });
  });

  group('license not accepted', () {
498
    testWithoutContext('pattern', () {
499 500 501 502 503 504 505 506 507 508 509
      expect(
        licenseNotAcceptedHandler.test(
          'You have not accepted the license agreements of the following SDK components'
        ),
        isTrue,
      );
    });

    testUsingContext('handler', () async {
      await licenseNotAcceptedHandler.handler(
        line: 'You have not accepted the license agreements of the following SDK components: [foo, bar]',
510
        project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
511 512 513
      );

      expect(
514
        testLogger.statusText,
515 516 517 518 519 520 521 522 523 524 525 526
        contains(
          'Unable to download needed Android SDK components, as the '
          'following licenses have not been accepted:\n'
          'foo, bar\n\n'
          'To resolve this, please run the following command in a Terminal:\n'
          'flutter doctor --android-licenses'
        )
      );
    });
  });

  group('flavor undefined', () {
527
    FakeProcessManager fakeProcessManager;
528 529

    setUp(() {
530
      fakeProcessManager = FakeProcessManager.list(<FakeCommand>[]);
531 532
    });

533
    testWithoutContext('pattern', () {
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
      expect(
        flavorUndefinedHandler.test(
          'Task assembleFooRelease not found in root project.'
        ),
        isTrue,
      );
      expect(
        flavorUndefinedHandler.test(
          'Task assembleBarRelease not found in root project.'
        ),
        isTrue,
      );
      expect(
        flavorUndefinedHandler.test(
          'Task assembleBar not found in root project.'
        ),
        isTrue,
      );
      expect(
        flavorUndefinedHandler.test(
          'Task assembleBar_foo not found in root project.'
        ),
        isTrue,
      );
    });

    testUsingContext('handler - with flavor', () async {
561 562 563 564 565 566
      fakeProcessManager.addCommand(const FakeCommand(
        command: <String>[
      'gradlew',
        'app:tasks' ,
        '--all',
        '--console=auto',
567
        ],
568
        stdout: '''
569 570 571 572 573 574 575 576 577 578
assembleRelease
assembleFlavor1
assembleFlavor1Release
assembleFlavor_2
assembleFlavor_2Release
assembleDebug
assembleProfile
assembles
assembleFooTest
          ''',
579
      ));
580 581

      await flavorUndefinedHandler.handler(
582
        project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
583 584 585
      );

      expect(
586
        testLogger.statusText,
587 588 589 590 591 592
        contains(
          'Gradle project does not define a task suitable '
          'for the requested build.'
        )
      );
      expect(
593
        testLogger.statusText,
594 595 596 597 598 599
        contains(
          'The android/app/build.gradle file defines product '
          'flavors: flavor1, flavor_2 '
          'You must specify a --flavor option to select one of them.'
        )
      );
600
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
601 602 603
    }, overrides: <Type, Generator>{
      GradleUtils: () => FakeGradleUtils(),
      Platform: () => fakePlatform('android'),
604
      ProcessManager: () => fakeProcessManager,
605
      FileSystem: () => MemoryFileSystem.test(),
606 607 608
    });

    testUsingContext('handler - without flavor', () async {
609 610
      fakeProcessManager.addCommand(const FakeCommand(
        command: <String>[
611 612 613 614 615
          'gradlew',
          'app:tasks' ,
          '--all',
          '--console=auto',
        ],
616
        stdout: '''
617 618 619 620
assembleRelease
assembleDebug
assembleProfile
          ''',
621
      ));
622 623

      await flavorUndefinedHandler.handler(
624
        project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
625 626 627
      );

      expect(
628
        testLogger.statusText,
629 630 631 632 633 634
        contains(
          'Gradle project does not define a task suitable '
          'for the requested build.'
        )
      );
      expect(
635
        testLogger.statusText,
636 637 638 639 640
        contains(
          'The android/app/build.gradle file does not define any custom product flavors. '
          'You cannot use the --flavor option.'
        )
      );
641
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
642 643 644
    }, overrides: <Type, Generator>{
      GradleUtils: () => FakeGradleUtils(),
      Platform: () => fakePlatform('android'),
645
      ProcessManager: () => fakeProcessManager,
646
      FileSystem: () => MemoryFileSystem.test(),
647 648 649 650
    });
  });
}

651
bool formatTestErrorMessage(String errorMessage, GradleHandledError error) {
652 653 654 655 656 657
  return errorMessage
    .split('\n')
    .any((String line) => error.test(line));
}

Platform fakePlatform(String name) {
658
  return FakePlatform(
659 660 661
    environment: <String, String>{
      'HOME': '/',
    },
662 663
    operatingSystem: name,
  );
664 665 666 667 668 669 670 671
}

class FakeGradleUtils extends GradleUtils {
  @override
  String getExecutable(FlutterProject project) {
    return 'gradlew';
  }
}