• Victoria Ashworth's avatar
    Fix log filtering and CI tests for iOS 17 physical devices (#132491) · ec0b7443
    Victoria Ashworth authored
    Fixes a couple of issues introduced in new iOS 17 physical device tooling: https://github.com/flutter/flutter/pull/131865.
    
    1) Duplicate messages were being filtered out too aggressively. 
    
    For example, if on the counter app, you printed "Increment!" on button click, it would only print once no matter how many times you clicked.
    
    Sometimes more than one log source is used at a time and the original intention was to filter duplicates between two log sources, so it wouldn't print the same message from both logs. However, it would also filter when the same message was added more than once via the same log.
    
    The new solution distinguishes a "primary" and a "fallback" log source and prefers to use the primary source unless it's not working, in which it'll use the fallback. If the fallback is faster than the primary, the primary will exclude the logs received by the fallback in a 1-to-1 fashion to prevent too-aggressive filtering. Once a flutter-message has been received by the primary source, fallback messages will be ignored.
    
    Note: iOS < 17 did not regress.
    
    2) There was a race condition between the shutdown hooks and exiting XcodeDebug that was causing a crash when deleting a file that doesn't exist. This only affects CI  - for the new integration tests and when testing with iOS 17 physical devices.
    ec0b7443
ios_device_logger_test.dart 37.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 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 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 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 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
// 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 'dart:async';

import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/async_guard.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/ios/devices.dart';
import 'package:flutter_tools/src/ios/ios_deploy.dart';
import 'package:flutter_tools/src/ios/mac.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart';

import '../../src/common.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fake_vm_services.dart';

void main() {
  late FakeProcessManager processManager;
  late Artifacts artifacts;
  late Cache fakeCache;
  late BufferLogger logger;
  late String ideviceSyslogPath;

  setUp(() {
    processManager = FakeProcessManager.empty();
    fakeCache = Cache.test(processManager: FakeProcessManager.any());
    artifacts = Artifacts.test();
    logger = BufferLogger.test();
    ideviceSyslogPath = artifacts.getHostArtifact(HostArtifact.idevicesyslog).path;
  });

  group('syslog stream', () {
    testWithoutContext('decodeSyslog decodes a syslog-encoded line', () {
      final String decoded = decodeSyslog(
          r'I \M-b\M^]\M-$\M-o\M-8\M^O syslog '
          r'\M-B\M-/\134_(\M-c\M^C\M^D)_/\M-B\M-/ \M-l\M^F\240!');

      expect(decoded, r'I ❤️ syslog ¯\_(ツ)_/¯ 솠!');
    });

    testWithoutContext('decodeSyslog passes through un-decodeable lines as-is', () {
      final String decoded = decodeSyslog(r'I \M-b\M^O syslog!');

      expect(decoded, r'I \M-b\M^O syslog!');
    });

    testWithoutContext('IOSDeviceLogReader suppresses non-Flutter lines from output with syslog', () async {
      processManager.addCommand(
        FakeCommand(
            command: <String>[
              ideviceSyslogPath, '-u', '1234',
            ],
            stdout: '''
Runner(Flutter)[297] <Notice>: A is for ari
Runner(libsystem_asl.dylib)[297] <Notice>: libMobileGestalt MobileGestaltSupport.m:153: pid 123 (Runner) does not have sandbox access for frZQaeyWLUvLjeuEK43hmg and IS NOT appropriately entitled
Runner(libsystem_asl.dylib)[297] <Notice>: libMobileGestalt MobileGestalt.c:550: no access to InverseDeviceID (see <rdar://problem/11744455>)
Runner(Flutter)[297] <Notice>: I is for ichigo
Runner(UIKit)[297] <Notice>: E is for enpitsu"
'''
        ),
      );
      final DeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
      );
      final List<String> lines = await logReader.logLines.toList();

      expect(lines, <String>['A is for ari', 'I is for ichigo']);
    });

    testWithoutContext('IOSDeviceLogReader includes multi-line Flutter logs in the output with syslog', () async {
      processManager.addCommand(
        FakeCommand(
            command: <String>[
              ideviceSyslogPath, '-u', '1234',
            ],
            stdout: '''
Runner(Flutter)[297] <Notice>: This is a multi-line message,
  with another Flutter message following it.
Runner(Flutter)[297] <Notice>: This is a multi-line message,
  with a non-Flutter log message following it.
Runner(libsystem_asl.dylib)[297] <Notice>: libMobileGestalt
'''
        ),
      );
      final DeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
      );
      final List<String> lines = await logReader.logLines.toList();

      expect(lines, <String>[
        'This is a multi-line message,',
        '  with another Flutter message following it.',
        'This is a multi-line message,',
        '  with a non-Flutter log message following it.',
      ]);
    });

    testWithoutContext('includes multi-line Flutter logs in the output', () async {
      processManager.addCommand(
        FakeCommand(
          command: <String>[
            ideviceSyslogPath, '-u', '1234',
          ],
          stdout: '''
Runner(Flutter)[297] <Notice>: This is a multi-line message,
  with another Flutter message following it.
Runner(Flutter)[297] <Notice>: This is a multi-line message,
  with a non-Flutter log message following it.
Runner(libsystem_asl.dylib)[297] <Notice>: libMobileGestalt
''',
        ),
      );

      final DeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
      );
      final List<String> lines = await logReader.logLines.toList();

      expect(lines, <String>[
        'This is a multi-line message,',
        '  with another Flutter message following it.',
        'This is a multi-line message,',
        '  with a non-Flutter log message following it.',
      ]);
    });
  });

  group('VM service', () {
    testWithoutContext('IOSDeviceLogReader can listen to VM Service logs', () async {
      final Event stdoutEvent = Event(
        kind: 'Stdout',
        timestamp: 0,
        bytes: base64.encode(utf8.encode('  This is a message ')),
      );
      final Event stderrEvent = Event(
        kind: 'Stderr',
        timestamp: 0,
        bytes: base64.encode(utf8.encode('  And this is an error ')),
      );
      final FlutterVmService vmService = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Debug',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stdout',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stderr',
        }),
        FakeVmServiceStreamResponse(event: stdoutEvent, streamId: 'Stdout'),
        FakeVmServiceStreamResponse(event: stderrEvent, streamId: 'Stderr'),
      ]).vmService;
      final DeviceLogReader logReader = IOSDeviceLogReader.test(
        useSyslog: false,
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
      );
      logReader.connectedVMService = vmService;

      // Wait for stream listeners to fire.
      await expectLater(logReader.logLines, emitsInAnyOrder(<Matcher>[
        equals('  This is a message '),
        equals('  And this is an error '),
      ]));
    });

    testWithoutContext('IOSDeviceLogReader ignores VM Service logs when attached to and received flutter logs from debugger', () async {
      final Event stdoutEvent = Event(
        kind: 'Stdout',
        timestamp: 0,
        bytes: base64.encode(utf8.encode('  This is a message ')),
      );
      final Event stderrEvent = Event(
        kind: 'Stderr',
        timestamp: 0,
        bytes: base64.encode(utf8.encode('  And this is an error ')),
      );
      final FlutterVmService vmService = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Debug',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stdout',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stderr',
        }),
        FakeVmServiceStreamResponse(event: stdoutEvent, streamId: 'Stdout'),
        FakeVmServiceStreamResponse(event: stderrEvent, streamId: 'Stderr'),
      ]).vmService;
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        useSyslog: false,
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
      );
      logReader.connectedVMService = vmService;

      final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
      iosDeployDebugger.debuggerAttached = true;

      final Stream<String> debuggingLogs = Stream<String>.fromIterable(<String>[
        'flutter: Message from debugger',
      ]);
      iosDeployDebugger.logLines = debuggingLogs;
      logReader.debuggerStream = iosDeployDebugger;

      // Wait for stream listeners to fire.
      await expectLater(logReader.logLines, emitsInAnyOrder(<Matcher>[
        equals('flutter: Message from debugger'),
      ]));
    });
  });

  group('debugger stream', () {
    testWithoutContext('IOSDeviceLogReader removes metadata prefix from lldb output', () async {
      final Stream<String> debuggingLogs = Stream<String>.fromIterable(<String>[
        '2020-09-15 19:15:10.931434-0700 Runner[541:226276] Did finish launching.',
        '2020-09-15 19:15:10.931434-0700 Runner[541:226276] [Category] Did finish launching from logging category.',
        'stderr from dart',
        '',
      ]);

      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        useSyslog: false,
      );
      final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
      iosDeployDebugger.logLines = debuggingLogs;
      logReader.debuggerStream = iosDeployDebugger;
      final Future<List<String>> logLines = logReader.logLines.toList();

      expect(await logLines, <String>[
        'Did finish launching.',
        '[Category] Did finish launching from logging category.',
        'stderr from dart',
        '',
      ]);
    });

    testWithoutContext('errors on debugger stream closes log stream', () async {
      final Stream<String> debuggingLogs = Stream<String>.error('ios-deploy error');
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        useSyslog: false,
      );
      final Completer<void> streamComplete = Completer<void>();
      final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
      iosDeployDebugger.logLines = debuggingLogs;
      logReader.logLines.listen(null, onError: (Object error) => streamComplete.complete());
      logReader.debuggerStream = iosDeployDebugger;

      await streamComplete.future;
    });

    testWithoutContext('detaches debugger', () async {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        useSyslog: false,
      );
      final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
      logReader.debuggerStream = iosDeployDebugger;

      logReader.dispose();
      expect(iosDeployDebugger.detached, true);
    });

    testWithoutContext('Does not throw if debuggerStream set after logReader closed', () async {
      final Stream<String> debuggingLogs = Stream<String>.fromIterable(<String>[
        '2020-09-15 19:15:10.931434-0700 Runner[541:226276] Did finish launching.',
        '2020-09-15 19:15:10.931434-0700 Runner[541:226276] [Category] Did finish launching from logging category.',
        'stderr from dart',
        '',
      ]);

      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        useSyslog: false,
      );
      Object? exception;
      StackTrace? trace;
      await asyncGuard(
          () async {
            await logReader.linesController.close();
            final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
            iosDeployDebugger.logLines = debuggingLogs;
            logReader.debuggerStream = iosDeployDebugger;
            await logReader.logLines.drain<void>();
          },
          onError: (Object err, StackTrace stackTrace) {
            exception = err;
            trace = stackTrace;
          }
      );
      expect(
        exception,
        isNull,
        reason: trace.toString(),
      );
    });
  });

  group('Determine which loggers to use', () {
    testWithoutContext('for physically attached CoreDevice', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        majorSdkVersion: 17,
        isCoreDevice: true,
      );

      expect(logReader.useSyslogLogging, isTrue);
      expect(logReader.useUnifiedLogging, isTrue);
      expect(logReader.useIOSDeployLogging, isFalse);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.idevicesyslog);
      expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.unifiedLogging);
    });

    testWithoutContext('for wirelessly attached CoreDevice', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        majorSdkVersion: 17,
        isCoreDevice: true,
        isWirelesslyConnected: true,
      );

      expect(logReader.useSyslogLogging, isFalse);
      expect(logReader.useUnifiedLogging, isTrue);
      expect(logReader.useIOSDeployLogging, isFalse);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.unifiedLogging);
      expect(logReader.logSources.fallbackSource, isNull);
    });

    testWithoutContext('for iOS 12 or less device', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        majorSdkVersion: 12,
      );

      expect(logReader.useSyslogLogging, isTrue);
      expect(logReader.useUnifiedLogging, isFalse);
      expect(logReader.useIOSDeployLogging, isFalse);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.idevicesyslog);
      expect(logReader.logSources.fallbackSource, isNull);
    });

    testWithoutContext('for iOS 13 or greater non-CoreDevice and _iosDeployDebugger not attached', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        majorSdkVersion: 13,
      );

      expect(logReader.useSyslogLogging, isFalse);
      expect(logReader.useUnifiedLogging, isTrue);
      expect(logReader.useIOSDeployLogging, isTrue);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
      expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.unifiedLogging);
    });

    testWithoutContext('for iOS 13 or greater non-CoreDevice, _iosDeployDebugger not attached, and VM is connected', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        majorSdkVersion: 13,
      );

      final FlutterVmService vmService = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Debug',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stdout',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stderr',
        }),
      ]).vmService;

      logReader.connectedVMService = vmService;

      expect(logReader.useSyslogLogging, isFalse);
      expect(logReader.useUnifiedLogging, isTrue);
      expect(logReader.useIOSDeployLogging, isTrue);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.unifiedLogging);
      expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.iosDeploy);
    });

    testWithoutContext('for iOS 13 or greater non-CoreDevice and _iosDeployDebugger is attached', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        majorSdkVersion: 13,
      );

      final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
      iosDeployDebugger.debuggerAttached = true;
      logReader.debuggerStream = iosDeployDebugger;

      final FlutterVmService vmService = FakeVmServiceHost(requests: <VmServiceExpectation>[
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Debug',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stdout',
        }),
        const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
          'streamId': 'Stderr',
        }),
      ]).vmService;

      logReader.connectedVMService = vmService;

      expect(logReader.useSyslogLogging, isFalse);
      expect(logReader.useUnifiedLogging, isTrue);
      expect(logReader.useIOSDeployLogging, isTrue);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
      expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.unifiedLogging);
    });

    testWithoutContext('for iOS 16 or greater non-CoreDevice', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        majorSdkVersion: 16,
      );

      final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
      iosDeployDebugger.debuggerAttached = true;
      logReader.debuggerStream = iosDeployDebugger;

      expect(logReader.useSyslogLogging, isFalse);
      expect(logReader.useUnifiedLogging, isTrue);
      expect(logReader.useIOSDeployLogging, isTrue);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
      expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.unifiedLogging);
    });

    testWithoutContext('for iOS 16 or greater non-CoreDevice in CI', () {
      final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
        iMobileDevice: IMobileDevice(
          artifacts: artifacts,
          processManager: processManager,
          cache: fakeCache,
          logger: logger,
        ),
        usingCISystem: true,
        majorSdkVersion: 16,
      );

      expect(logReader.useSyslogLogging, isTrue);
      expect(logReader.useUnifiedLogging, isFalse);
      expect(logReader.useIOSDeployLogging, isTrue);
      expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
      expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.idevicesyslog);
    });

    group('when useSyslogLogging', () {

      testWithoutContext('is true syslog sends flutter messages to stream', () async {
        processManager.addCommand(
          FakeCommand(
              command: <String>[
                ideviceSyslogPath, '-u', '1234',
              ],
              stdout: '''
  Runner(Flutter)[297] <Notice>: A is for ari
  Runner(Flutter)[297] <Notice>: I is for ichigo
  May 30 13:56:28 Runner(Flutter)[2037] <Notice>: flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/
  May 30 13:56:28 Runner(Flutter)[2037] <Notice>: flutter: This is a test
  May 30 13:56:28 Runner(Flutter)[2037] <Notice>: [VERBOSE-2:FlutterDarwinContextMetalImpeller.mm(39)] Using the Impeller rendering backend.
  '''
          ),
        );
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: processManager,
            cache: fakeCache,
            logger: logger,
          ),
          usingCISystem: true,
          majorSdkVersion: 16,
        );
        final List<String> lines = await logReader.logLines.toList();

        expect(logReader.useSyslogLogging, isTrue);
        expect(processManager, hasNoRemainingExpectations);
        expect(lines, <String>[
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/',
          'flutter: This is a test'
        ]);
      });

      testWithoutContext('is false syslog does not send flutter messages to stream', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: processManager,
            cache: fakeCache,
            logger: logger,
          ),
          majorSdkVersion: 16,
        );

        final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
        iosDeployDebugger.logLines =  Stream<String>.fromIterable(<String>[]);
        logReader.debuggerStream = iosDeployDebugger;

        final List<String> lines = await logReader.logLines.toList();

        expect(logReader.useSyslogLogging, isFalse);
        expect(processManager, hasNoRemainingExpectations);
        expect(lines, isEmpty);
      });
    });

    group('when useIOSDeployLogging', () {

      testWithoutContext('is true ios-deploy sends flutter messages to stream', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: processManager,
            cache: fakeCache,
            logger: logger,
          ),
          majorSdkVersion: 16,
        );

        final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
        final Stream<String> debuggingLogs = Stream<String>.fromIterable(<String>[
          'flutter: Message from debugger',
        ]);
        iosDeployDebugger.logLines = debuggingLogs;
        logReader.debuggerStream = iosDeployDebugger;

        final List<String> lines = await logReader.logLines.toList();

        expect(logReader.useIOSDeployLogging, isTrue);
        expect(processManager, hasNoRemainingExpectations);
        expect(lines, <String>[
          'flutter: Message from debugger',
        ]);
      });

      testWithoutContext('is false ios-deploy does not send flutter messages to stream', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: FakeProcessManager.any(),
            cache: fakeCache,
            logger: logger,
          ),
          majorSdkVersion: 12,
        );

        final FakeIOSDeployDebugger iosDeployDebugger = FakeIOSDeployDebugger();
        final Stream<String> debuggingLogs = Stream<String>.fromIterable(<String>[
          'flutter: Message from debugger',
        ]);
        iosDeployDebugger.logLines = debuggingLogs;
        logReader.debuggerStream = iosDeployDebugger;

        final List<String> lines = await logReader.logLines.toList();

        expect(logReader.useIOSDeployLogging, isFalse);
        expect(processManager, hasNoRemainingExpectations);
        expect(lines, isEmpty);
      });
    });

    group('when useUnifiedLogging', () {


      testWithoutContext('is true Dart VM sends flutter messages to stream', () async {
        final Event stdoutEvent = Event(
          kind: 'Stdout',
          timestamp: 0,
          bytes: base64.encode(utf8.encode('flutter: A flutter message')),
        );
        final Event stderrEvent = Event(
          kind: 'Stderr',
          timestamp: 0,
          bytes: base64.encode(utf8.encode('flutter: A second flutter message')),
        );
        final FlutterVmService vmService = FakeVmServiceHost(requests: <VmServiceExpectation>[
          const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
            'streamId': 'Debug',
          }),
          const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
            'streamId': 'Stdout',
          }),
          const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
            'streamId': 'Stderr',
          }),
          FakeVmServiceStreamResponse(event: stdoutEvent, streamId: 'Stdout'),
          FakeVmServiceStreamResponse(event: stderrEvent, streamId: 'Stderr'),
        ]).vmService;
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          useSyslog: false,
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: processManager,
            cache: fakeCache,
            logger: logger,
          ),
        );
        logReader.connectedVMService = vmService;

        // Wait for stream listeners to fire.
        expect(logReader.useUnifiedLogging, isTrue);
        expect(processManager, hasNoRemainingExpectations);
        await expectLater(logReader.logLines, emitsInAnyOrder(<Matcher>[
          equals('flutter: A flutter message'),
          equals('flutter: A second flutter message'),
        ]));
      });

      testWithoutContext('is false Dart VM does not send flutter messages to stream', () async {
        final Event stdoutEvent = Event(
          kind: 'Stdout',
          timestamp: 0,
          bytes: base64.encode(utf8.encode('flutter: A flutter message')),
        );
        final Event stderrEvent = Event(
          kind: 'Stderr',
          timestamp: 0,
          bytes: base64.encode(utf8.encode('flutter: A second flutter message')),
        );
        final FlutterVmService vmService = FakeVmServiceHost(requests: <VmServiceExpectation>[
          const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
            'streamId': 'Debug',
          }),
          const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
            'streamId': 'Stdout',
          }),
          const FakeVmServiceRequest(method: 'streamListen', args: <String, Object>{
            'streamId': 'Stderr',
          }),
          FakeVmServiceStreamResponse(event: stdoutEvent, streamId: 'Stdout'),
          FakeVmServiceStreamResponse(event: stderrEvent, streamId: 'Stderr'),
        ]).vmService;
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: FakeProcessManager.any(),
            cache: fakeCache,
            logger: logger,
          ),
          majorSdkVersion: 12,
        );
        logReader.connectedVMService = vmService;

        final List<String> lines = await logReader.logLines.toList();

        // Wait for stream listeners to fire.
        expect(logReader.useUnifiedLogging, isFalse);
        expect(processManager, hasNoRemainingExpectations);
        expect(lines, isEmpty);
      });
    });

    group('and when to exclude logs:', () {

      testWithoutContext('all primary messages are included except if fallback sent flutter message first', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: FakeProcessManager.any(),
            cache: fakeCache,
            logger: logger,
          ),
          usingCISystem: true,
          majorSdkVersion: 16,
        );

        expect(logReader.useSyslogLogging, isTrue);
        expect(logReader.useIOSDeployLogging, isTrue);
        expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
        expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.idevicesyslog);

        final Future<List<String>> logLines = logReader.logLines.toList();

        logReader.addToLinesController(
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/',
          IOSDeviceLogSource.idevicesyslog,
        );
        // Will be excluded because was already added by fallback.
        logReader.addToLinesController(
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/',
          IOSDeviceLogSource.iosDeploy,
        );
        logReader.addToLinesController(
          'A second non-flutter message',
          IOSDeviceLogSource.iosDeploy,
        );
        logReader.addToLinesController(
          'flutter: Another flutter message',
          IOSDeviceLogSource.iosDeploy,
        );
        final List<String> lines = await logLines;

        expect(lines, containsAllInOrder(<String>[
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/', // from idevicesyslog
          'A second non-flutter message', // from iosDeploy
          'flutter: Another flutter message', // from iosDeploy
        ]));
      });

      testWithoutContext('all primary messages are included when there is no fallback', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: FakeProcessManager.any(),
            cache: fakeCache,
            logger: logger,
          ),
          majorSdkVersion: 12,
        );

        expect(logReader.useSyslogLogging, isTrue);
        expect(logReader.logSources.primarySource, IOSDeviceLogSource.idevicesyslog);
        expect(logReader.logSources.fallbackSource, isNull);

        final Future<List<String>> logLines = logReader.logLines.toList();

        logReader.addToLinesController(
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/',
          IOSDeviceLogSource.idevicesyslog,
        );
        logReader.addToLinesController(
          'A non-flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        logReader.addToLinesController(
          'A non-flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        final List<String> lines = await logLines;

        expect(lines, containsAllInOrder(<String>[
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/',
          'A non-flutter message',
          'A non-flutter message',
          'flutter: A flutter message',
          'flutter: A flutter message',
        ]));
      });

      testWithoutContext('primary messages are not added if fallback already added them, otherwise duplicates are allowed', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: FakeProcessManager.any(),
            cache: fakeCache,
            logger: logger,
          ),
          usingCISystem: true,
          majorSdkVersion: 16,
        );

        expect(logReader.useSyslogLogging, isTrue);
        expect(logReader.useIOSDeployLogging, isTrue);
        expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
        expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.idevicesyslog);

        final Future<List<String>> logLines = logReader.logLines.toList();

        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        logReader.addToLinesController(
          'A non-flutter message',
          IOSDeviceLogSource.iosDeploy,
        );
        logReader.addToLinesController(
          'A non-flutter message',
          IOSDeviceLogSource.iosDeploy,
        );
        // Will be excluded because was already added by fallback.
        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.iosDeploy,
        );
        // Will be excluded because was already added by fallback.
        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.iosDeploy,
        );
        // Will be included because, although the message is the same, the
        // fallback only added it twice so this third one is considered new.
        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.iosDeploy,
        );

        final List<String> lines = await logLines;

        expect(lines, containsAllInOrder(<String>[
          'flutter: A flutter message', // from idevicesyslog
          'flutter: A flutter message', // from idevicesyslog
          'A non-flutter message', // from iosDeploy
          'A non-flutter message', // from iosDeploy
          'flutter: A flutter message', // from iosDeploy
        ]));
      });

      testWithoutContext('flutter fallback messages are included until a primary flutter message is received', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: FakeProcessManager.any(),
            cache: fakeCache,
            logger: logger,
          ),
          usingCISystem: true,
          majorSdkVersion: 16,
        );

        expect(logReader.useSyslogLogging, isTrue);
        expect(logReader.useIOSDeployLogging, isTrue);
        expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
        expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.idevicesyslog);

        final Future<List<String>> logLines = logReader.logLines.toList();

        logReader.addToLinesController(
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/',
          IOSDeviceLogSource.idevicesyslog,
        );
        logReader.addToLinesController(
          'A second non-flutter message',
          IOSDeviceLogSource.iosDeploy,
        );
        // Will be included because the first log from primary source wasn't a
        // flutter log.
        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        // Will be excluded because was already added by fallback, however, it
        // will be used to determine a flutter log was received by the primary source.
        logReader.addToLinesController(
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/',
          IOSDeviceLogSource.iosDeploy,
        );
        // Will be excluded because flutter log from primary was received.
        logReader.addToLinesController(
          'flutter: A third flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );

        final List<String> lines = await logLines;

        expect(lines, containsAllInOrder(<String>[
          'flutter: The Dart VM service is listening on http://127.0.0.1:63098/35ZezGIQLnw=/', // from idevicesyslog
          'A second non-flutter message', // from iosDeploy
          'flutter: A flutter message', // from idevicesyslog
        ]));
      });

      testWithoutContext('non-flutter fallback messages are not included', () async {
        final IOSDeviceLogReader logReader = IOSDeviceLogReader.test(
          iMobileDevice: IMobileDevice(
            artifacts: artifacts,
            processManager: FakeProcessManager.any(),
            cache: fakeCache,
            logger: logger,
          ),
          usingCISystem: true,
          majorSdkVersion: 16,
        );

        expect(logReader.useSyslogLogging, isTrue);
        expect(logReader.useIOSDeployLogging, isTrue);
        expect(logReader.logSources.primarySource, IOSDeviceLogSource.iosDeploy);
        expect(logReader.logSources.fallbackSource, IOSDeviceLogSource.idevicesyslog);

        final Future<List<String>> logLines = logReader.logLines.toList();

        logReader.addToLinesController(
          'flutter: A flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );
        // Will be excluded because it's from fallback and not a flutter message.
        logReader.addToLinesController(
          'A non-flutter message',
          IOSDeviceLogSource.idevicesyslog,
        );

        final List<String> lines = await logLines;

        expect(lines, containsAllInOrder(<String>[
          'flutter: A flutter message',
        ]));
      });
    });
  });
}

class FakeIOSDeployDebugger extends Fake implements IOSDeployDebugger {
  bool detached = false;

  @override
  bool debuggerAttached = false;

  @override
  Stream<String> logLines = const Stream<String>.empty();

  @override
  void detach() {
    detached = true;
  }
}