5 #import <Foundation/Foundation.h>
6 #import <OCMock/OCMock.h>
7 #import <XCTest/XCTest.h>
9 #import <objc/runtime.h>
11 #import "flutter/common/settings.h"
12 #include "flutter/fml/synchronization/sync_switch.h"
13 #include "flutter/lib/ui/window/platform_message.h"
14 #include "flutter/lib/ui/window/platform_message_response.h"
15 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
18 #import "flutter/shell/platform/darwin/common/test_utils_swift/test_utils_swift.h"
19 #import "flutter/shell/platform/darwin/ios/InternalFlutterSwift/InternalFlutterSwift.h"
37 static fml::RefPtr<TestPlatformMessageResponse>
Create() {
40 void Complete(std::unique_ptr<fml::Mapping> data)
override { is_complete_ =
true; }
50 UIScreen* screen = OCMClassMock([UIScreen
class]);
51 OCMStub([screen nativeBounds]).andDo(^(NSInvocation* invocation) {
52 CGRect nativeBounds = CGRectMake(0, 0, screenNativeSize.width, screenNativeSize.height);
53 [invocation setReturnValue:&nativeBounds];
55 OCMStub([screen scale]).andDo(^(NSInvocation* invocation) {
56 CGFloat scale = screenScale;
57 [invocation setReturnValue:&scale];
59 UIWindowScene* windowScene = OCMClassMock([UIWindowScene
class]);
60 OCMStub([windowScene screen]).andReturn(screen);
61 UIWindow* window = OCMClassMock([UIWindow
class]);
62 OCMStub([window windowScene]).andReturn(windowScene);
63 UIView* view = OCMClassMock([UIView
class]);
64 OCMStub([view window]).andReturn(window);
90 + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
95 @property(nonatomic) BOOL ensureSemanticsEnabledCalled;
101 _ensureSemanticsEnabledCalled = YES;
115 @property(nonatomic, assign) BOOL failOnDealloc;
120 if (_failOnDealloc) {
121 XCTFail(
"FakeBinaryMessageRelay should not be deallocated");
143 - (void)testShellGetters {
149 XCTAssertNil(
engine.platformTaskRunner);
150 XCTAssertNil(
engine.uiTaskRunner);
151 XCTAssertNil(
engine.rasterTaskRunner);
154 - (void)testTaskRunnerPropertyStability {
161 XCTAssertNotNil(
engine.platformTaskRunner);
162 XCTAssertEqual(
engine.platformTaskRunner,
engine.platformTaskRunner);
163 XCTAssertNotNil(
engine.uiTaskRunner);
164 XCTAssertEqual(
engine.uiTaskRunner,
engine.uiTaskRunner);
165 XCTAssertNotNil(
engine.rasterTaskRunner);
166 XCTAssertEqual(
engine.rasterTaskRunner,
engine.rasterTaskRunner);
169 - (void)testRunOnRunningEngineIsRefused {
171 XCTAssertTrue([
engine run]);
175 XCTAssertFalse([
engine run]);
176 XCTAssertEqual(
engine.platformTaskRunner, platformTaskRunner);
179 - (void)testRunWithDifferentEntrypointOnRunningEngineIsRefused {
181 XCTAssertTrue([
engine run]);
184 XCTAssertFalse([
engine runWithEntrypoint:
@"someOtherEntrypoint"]);
187 - (void)testRunAfterDestroyContextIsRefused {
189 XCTAssertTrue([
engine run]);
194 XCTAssertFalse([
engine run]);
195 XCTAssertNil(
engine.platformTaskRunner);
196 XCTAssertNil(
engine.uiTaskRunner);
197 XCTAssertNil(
engine.rasterTaskRunner);
200 - (void)testDestroyContextIsIdempotent {
202 XCTAssertTrue([
engine run]);
208 XCTAssertNil(
engine.platformTaskRunner);
211 - (void)testTextureCallbacksAfterDestroyContextAreIgnored {
213 XCTAssertTrue([
engine run]);
214 NSObject<FlutterTextureRegistry>* textures = [[engine
registrarForPlugin:@"test"] textures];
220 [textures textureFrameAvailable:textureId];
221 [textures unregisterTexture:textureId];
224 - (void)testInfoPlist {
226 NSURL* flutterFrameworkURL =
227 [NSBundle.mainBundle.privateFrameworksURL URLByAppendingPathComponent:@"Flutter.framework"];
228 NSBundle* flutterBundle = [NSBundle bundleWithURL:flutterFrameworkURL];
229 XCTAssertEqualObjects(flutterBundle.bundleIdentifier,
@"io.flutter.flutter");
231 NSDictionary<NSString*, id>* infoDictionary = flutterBundle.infoDictionary;
234 NSError* regexError = NULL;
235 NSRegularExpression* osVersionRegex =
236 [NSRegularExpression regularExpressionWithPattern:@"((0|[1-9]\\d*)\\.)*(0|[1-9]\\d*)"
237 options:NSRegularExpressionCaseInsensitive
239 XCTAssertNil(regexError);
242 NSString* testString =
@"9";
243 NSUInteger versionMatches =
244 [osVersionRegex numberOfMatchesInString:testString
245 options:NSMatchingAnchored
246 range:NSMakeRange(0, testString.length)];
247 XCTAssertEqual(versionMatches, 1UL);
249 versionMatches = [osVersionRegex numberOfMatchesInString:testString
250 options:NSMatchingAnchored
251 range:NSMakeRange(0, testString.length)];
252 XCTAssertEqual(versionMatches, 1UL);
253 testString =
@"9.0.1";
254 versionMatches = [osVersionRegex numberOfMatchesInString:testString
255 options:NSMatchingAnchored
256 range:NSMakeRange(0, testString.length)];
257 XCTAssertEqual(versionMatches, 1UL);
258 testString =
@".0.1";
259 versionMatches = [osVersionRegex numberOfMatchesInString:testString
260 options:NSMatchingAnchored
261 range:NSMakeRange(0, testString.length)];
262 XCTAssertEqual(versionMatches, 0UL);
265 NSString* minimumOSVersion = infoDictionary[@"MinimumOSVersion"];
266 versionMatches = [osVersionRegex numberOfMatchesInString:minimumOSVersion
267 options:NSMatchingAnchored
268 range:NSMakeRange(0, minimumOSVersion.length)];
269 XCTAssertEqual(versionMatches, 1UL);
272 XCTAssertEqual(((NSString*)infoDictionary[
@"FlutterEngine"]).length, 40UL);
277 XCTAssertTrue(((NSString*)infoDictionary[
@"ClangVersion"]).length > 15UL);
280 - (void)testDeallocated {
286 XCTAssertNotNil(weakEngine);
288 XCTAssertNil(weakEngine);
291 - (void)testSendMessageBeforeRun {
295 XCTAssertThrows([
engine.binaryMessenger
297 message:[
@"bar" dataUsingEncoding:NSUTF8StringEncoding]
301 - (void)testSetMessageHandlerBeforeRun {
305 XCTAssertThrows([
engine.binaryMessenger
306 setMessageHandlerOnChannel:
@"foo"
312 - (void)testNilSetMessageHandlerBeforeRun {
316 XCTAssertNoThrow([
engine.binaryMessenger setMessageHandlerOnChannel:
@"foo"
317 binaryMessageHandler:nil]);
320 - (void)testNotifyPluginOfDealloc {
322 OCMStub([plugin detachFromEngineForRegistrar:[OCMArg any]]);
327 [registrar publish:plugin];
329 OCMVerify([plugin detachFromEngineForRegistrar:[OCMArg any]]);
332 - (void)testGetViewControllerFromRegistrar {
335 id mockEngine = OCMPartialMock(
engine);
336 NSObject<FlutterPluginRegistrar>* registrar = [mockEngine registrarForPlugin:@"plugin"];
343 - (void)testSetBinaryMessengerToSameBinaryMessenger {
357 - (void)testRunningInitialRouteSendsNavigationMessage {
370 NSData* encodedSetInitialRouteMethod =
372 OCMVerify([mockBinaryMessenger sendOnChannel:
@"flutter/navigation"
373 message:encodedSetInitialRouteMethod]);
376 - (void)testInitialRouteSettingsSendsNavigationMessage {
380 settings.route =
"test";
390 NSData* encodedSetInitialRouteMethod =
392 OCMVerify([mockBinaryMessenger sendOnChannel:
@"flutter/navigation"
393 message:encodedSetInitialRouteMethod]);
396 - (void)testWaitForFirstFrameTimeout {
399 XCTestExpectation* timeoutFirstFrame = [
self expectationWithDescription:@"timeoutFirstFrame"];
402 if (timeoutFirstFrame) {
403 [timeoutFirstFrame fulfill];
406 [
self waitForExpectations:@[ timeoutFirstFrame ]];
416 XCTAssertNotNil(spawn);
419 - (void)testEngineId {
422 int64_t id1 =
engine.engineIdentifier;
423 XCTAssertTrue(id1 != 0);
425 XCTAssertEqual(registrar1.engineIdentifier, id1);
430 int64_t id2 = spawn.engineIdentifier;
432 XCTAssertEqual(registrar2.engineIdentifier, id2);
434 XCTAssertEqual([
FlutterEngine engineForIdentifier:id2], spawn);
437 - (void)testSetHandlerAfterRun {
439 XCTestExpectation* gotMessage = [
self expectationWithDescription:@"gotMessage"];
440 dispatch_async(dispatch_get_main_queue(), ^{
442 fml::AutoResetWaitableEvent latch;
444 flutter::Shell& shell =
engine.shell;
445 fml::TaskRunner::RunNowOrPostTask(
446 engine.shell.GetTaskRunners().GetUITaskRunner(), [&latch, &shell] {
447 flutter::Engine::Delegate& delegate = shell;
448 auto message = std::make_unique<flutter::PlatformMessage>(
"foo", nullptr);
449 delegate.OnEngineHandlePlatformMessage(std::move(message));
453 [registrar.messenger setMessageHandlerOnChannel:@"foo"
454 binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) {
455 [gotMessage fulfill];
458 [
self waitForExpectations:@[ gotMessage ]];
461 - (void)testThreadPrioritySetCorrectly {
462 XCTestExpectation* prioritiesSet = [
self expectationWithDescription:@"prioritiesSet"];
463 prioritiesSet.expectedFulfillmentCount = 2;
465 IMP mockSetThreadPriority =
466 imp_implementationWithBlock(^(NSThread* thread,
double threadPriority) {
467 if ([thread.name hasSuffix:
@".raster"]) {
468 XCTAssertEqual(threadPriority, 1.0);
469 [prioritiesSet fulfill];
470 }
else if ([thread.name hasSuffix:
@".io"]) {
471 XCTAssertEqual(threadPriority, 0.5);
472 [prioritiesSet fulfill];
475 Method method = class_getInstanceMethod([NSThread
class],
@selector(setThreadPriority:));
476 IMP originalSetThreadPriority = method_getImplementation(method);
477 method_setImplementation(method, mockSetThreadPriority);
481 [
self waitForExpectations:@[ prioritiesSet ]];
483 method_setImplementation(method, originalSetThreadPriority);
486 - (void)testCanEnableDisableEmbedderAPIThroughInfoPlist {
492 XCTAssertFalse(
engine.enableEmbedderAPI);
496 id mockMainBundle = OCMPartialMock([NSBundle mainBundle]);
497 OCMStub([mockMainBundle objectForInfoDictionaryKey:
@"FLTEnableIOSEmbedderAPI"])
502 XCTAssertTrue(
engine.enableEmbedderAPI);
506 - (void)testFlutterTextInputViewDidResignFirstResponderWillCallTextInputClientConnectionClosed {
511 [engine flutterTextInputView:nil didResignFirstResponderWithTextInputClient:1];
516 OCMVerify([mockBinaryMessenger sendOnChannel:
@"flutter/textinput" message:encodedMethodCall]);
519 - (void)testFlutterTextInputViewDidRestoreFirstResponderWillCallTextInputClientOnFocusReceived {
529 id mockBinaryReply = [OCMArg invokeBlockWithArgs:encodedReply, nil];
530 OCMStub([mockBinaryMessenger sendOnChannel:
@"flutter/textinput"
531 message:encodedMethodCall
532 binaryReply:mockBinaryReply]);
534 __block
id focusReceivedResult;
535 [engine flutterTextInputView:nil
536 didRestoreFirstResponderWithTextInputClient:123
537 result:^(id result) {
538 focusReceivedResult = result;
540 XCTAssertEqualObjects(focusReceivedResult, @NO);
543 - (void)testFlutterEngineUpdatesDisplays {
545 id mockEngine = OCMPartialMock(
engine);
548 OCMVerify(times(1), [mockEngine updateDisplays]);
549 engine.viewController = nil;
550 OCMVerify(times(2), [mockEngine updateDisplays]);
553 - (void)testUpdateDisplaysFallsBackToMainScreenBeforeViewIsInWindow {
555 id mockEngine = OCMPartialMock(
engine);
561 CGSize mainScreenNativeSize = UIScreen.mainScreen.nativeBounds.size;
562 CGFloat mainScreenScale = UIScreen.mainScreen.scale;
563 OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:mainScreenNativeSize
564 scale:mainScreenScale]);
567 - (void)testUpdateDisplaysUsesScreenOfViewWindow {
569 id mockEngine = OCMPartialMock(
engine);
571 OCMStub([mockEngine
viewController]).andDo(^(NSInvocation* invocation) {
573 [invocation setReturnValue:&value];
580 OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
583 - (void)testUpdateDisplaysDoesNotResendUnchangedDisplay {
585 id mockEngine = OCMPartialMock(
engine);
587 OCMStub([mockEngine
viewController]).andDo(^(NSInvocation* invocation) {
589 [invocation setReturnValue:&value];
600 OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
603 - (void)testUpdateDisplaysResendsWhenScreenChanges {
605 id mockEngine = OCMPartialMock(
engine);
607 OCMStub([mockEngine
viewController]).andDo(^(NSInvocation* invocation) {
609 [invocation setReturnValue:&value];
624 OCMVerify(times(2), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
625 OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(3003, 4004) scale:3]);
626 OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:2]);
629 - (void)testUpdateDisplaysKeepsLastDisplayWhenViewIsNotInWindow {
631 id mockEngine = OCMPartialMock(
engine);
633 OCMStub([mockEngine
viewController]).andDo(^(NSInvocation* invocation) {
635 [invocation setReturnValue:&value];
649 CGSize mainScreenNativeSize = UIScreen.mainScreen.nativeBounds.size;
650 CGFloat mainScreenScale = UIScreen.mainScreen.scale;
651 OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:mainScreenNativeSize
652 scale:mainScreenScale]);
653 OCMVerify(times(1), [mockEngine sendDisplayWithScreenNativeSize:CGSizeMake(1001, 2002) scale:3]);
656 - (void)testLifeCycleNotificationDidEnterBackgroundForApplication {
660 NSNotification* sceneNotification =
661 [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
664 NSNotification* applicationNotification =
665 [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification
668 id mockEngine = OCMPartialMock(
engine);
669 [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
670 [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
671 OCMVerify(times(1), [mockEngine applicationDidEnterBackground:[OCMArg any]]);
672 XCTAssertTrue(
engine.isGpuDisabled);
673 BOOL gpuDisabled = NO;
674 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
675 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
678 XCTAssertTrue(gpuDisabled);
681 - (void)testLifeCycleNotificationDidEnterBackgroundForScene {
682 id mockBundle = OCMPartialMock([NSBundle mainBundle]);
683 OCMStub([mockBundle objectForInfoDictionaryKey:
@"NSExtension"]).andReturn(@{
684 @"NSExtensionPointIdentifier" :
@"com.apple.share-services"
689 NSNotification* sceneNotification =
690 [NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
693 NSNotification* applicationNotification =
694 [NSNotification notificationWithName:UIApplicationDidEnterBackgroundNotification
697 id mockEngine = OCMPartialMock(
engine);
698 [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
699 [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
700 OCMVerify(times(1), [mockEngine sceneDidEnterBackground:[OCMArg any]]);
701 XCTAssertTrue(
engine.isGpuDisabled);
702 BOOL gpuDisabled = NO;
703 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
704 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
707 XCTAssertTrue(gpuDisabled);
708 [mockBundle stopMocking];
711 - (void)testLifeCycleNotificationWillEnterForegroundForApplication {
715 NSNotification* sceneNotification =
716 [NSNotification notificationWithName:UISceneWillEnterForegroundNotification
719 NSNotification* applicationNotification =
720 [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification
723 id mockEngine = OCMPartialMock(
engine);
724 [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
725 [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
726 OCMVerify(times(1), [mockEngine applicationWillEnterForeground:[OCMArg any]]);
727 XCTAssertFalse(
engine.isGpuDisabled);
728 BOOL gpuDisabled = YES;
729 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
730 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
733 XCTAssertFalse(gpuDisabled);
736 - (void)testLifeCycleNotificationWillEnterForegroundForScene {
737 id mockBundle = OCMPartialMock([NSBundle mainBundle]);
738 OCMStub([mockBundle objectForInfoDictionaryKey:
@"NSExtension"]).andReturn(@{
739 @"NSExtensionPointIdentifier" :
@"com.apple.share-services"
744 NSNotification* sceneNotification =
745 [NSNotification notificationWithName:UISceneWillEnterForegroundNotification
748 NSNotification* applicationNotification =
749 [NSNotification notificationWithName:UIApplicationWillEnterForegroundNotification
752 id mockEngine = OCMPartialMock(
engine);
753 [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
754 [NSNotificationCenter.defaultCenter postNotification:applicationNotification];
755 OCMVerify(times(1), [mockEngine sceneWillEnterForeground:[OCMArg any]]);
756 XCTAssertFalse(
engine.isGpuDisabled);
757 BOOL gpuDisabled = YES;
758 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
759 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
762 XCTAssertFalse(gpuDisabled);
763 [mockBundle stopMocking];
773 - (void)testGpuStateSetBeforeRunIsAppliedToShell {
777 engine.isGpuDisabled = YES;
778 XCTAssertTrue(
engine.isGpuDisabled);
782 XCTAssertTrue(
engine.isGpuDisabled);
784 BOOL gpuDisabled = NO;
785 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
786 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
789 XCTAssertTrue(gpuDisabled);
798 - (void)testGpuIsDisabledWhenCreatedWhileBackgrounded {
799 id mockApplication = OCMClassMock([UIApplication
class]);
800 OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
801 OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateBackground);
802 [
self addTeardownBlock:^{
803 [mockApplication stopMocking];
810 XCTAssertTrue(
engine.isGpuDisabled);
814 BOOL gpuDisabled = NO;
815 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
816 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
819 XCTAssertTrue(gpuDisabled);
833 - (void)testGpuIsEnabledWhenCreatedWhileForegrounded {
834 id mockApplication = OCMClassMock([UIApplication
class]);
835 OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
836 OCMStub([mockApplication applicationState]).andReturn(UIApplicationStateActive);
837 [
self addTeardownBlock:^{
838 [mockApplication stopMocking];
845 XCTAssertFalse(
engine.isGpuDisabled);
847 BOOL gpuDisabled = YES;
848 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
849 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
852 XCTAssertFalse(gpuDisabled);
856 engine.isGpuDisabled = YES;
857 engine.viewController = nil;
859 XCTAssertFalse(
engine.isGpuDisabled);
862 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
863 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
866 XCTAssertFalse(gpuDisabled);
881 - (void)testGpuStateIsPreservedWhenLifecycleStateIsUnknown {
887 id mockBundle = OCMPartialMock([NSBundle mainBundle]);
888 OCMStub([mockBundle objectForInfoDictionaryKey:
@"NSExtension"]).andReturn(@{
889 @"NSExtensionPointIdentifier" :
@"com.apple.share-services"
891 [
self addTeardownBlock:^{
892 [mockBundle stopMocking];
902 [[NSNotificationCenter defaultCenter]
903 postNotification:[NSNotification notificationWithName:UISceneDidEnterBackgroundNotification
906 XCTAssertTrue(
engine.isGpuDisabled);
909 engine.viewController = nil;
911 XCTAssertTrue(
engine.isGpuDisabled);
913 BOOL gpuDisabled = NO;
914 [engine
shell].GetIsGpuDisabledSyncSwitch()->Execute(
915 fml::SyncSwitch::Handlers().SetIfTrue([&] { gpuDisabled = YES; }).SetIfFalse([&] {
918 XCTAssertTrue(gpuDisabled);
935 - (void)testBackgroundTaskQueueDeliversOffThePlatformThread {
940 NSObject<FlutterTaskQueue>* taskQueue = [engine makeBackgroundTaskQueue];
941 XCTAssertNotNil(taskQueue);
943 NSString* channel =
@"com.example.background";
944 XCTestExpectation* didCallHandler = [
self expectationWithDescription:@"didCallHandler"];
946 [engine setMessageHandlerOnChannel:channel
947 binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply reply) {
948 XCTAssertFalse([NSThread isMainThread]);
950 [didCallHandler fulfill];
952 taskQueue:taskQueue];
953 XCTAssertTrue(connection > 0);
956 auto response = TestPlatformMessageResponse::Create();
957 engine.platformView->GetPlatformMessageHandlerIos()->HandlePlatformMessage(
958 std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response));
960 [
self waitForExpectationsWithTimeout:5.0 handler:nil];
961 XCTAssertTrue(response->is_complete());
963 [engine cleanUpConnection:connection];
977 - (void)testNilTaskQueueDeliversOnThePlatformThread {
982 NSString* channel =
@"com.example.platform";
983 XCTestExpectation* didCallHandler = [
self expectationWithDescription:@"didCallHandler"];
985 [engine setMessageHandlerOnChannel:channel
986 binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply reply) {
987 XCTAssertTrue([NSThread isMainThread]);
989 [didCallHandler fulfill];
992 XCTAssertTrue(connection > 0);
994 auto response = TestPlatformMessageResponse::Create();
995 engine.platformView->GetPlatformMessageHandlerIos()->HandlePlatformMessage(
996 std::make_unique<flutter::PlatformMessage>(channel.UTF8String, response));
998 [
self waitForExpectationsWithTimeout:5.0 handler:nil];
999 XCTAssertTrue(response->is_complete());
1001 [engine cleanUpConnection:connection];
1004 - (void)testLifeCycleNotificationSceneWillConnect {
1008 id mockScene = OCMClassMock([UIWindowScene
class]);
1011 OCMStub([mockScene delegate]).andReturn(mockLifecycleProvider);
1012 OCMStub([mockLifecycleProvider sceneLifeCycleDelegate]).andReturn(mockLifecycleDelegate);
1014 NSNotification* sceneNotification =
1015 [NSNotification notificationWithName:UISceneWillConnectNotification
1019 [NSNotificationCenter.defaultCenter postNotification:sceneNotification];
1020 OCMVerify(times(1), [mockLifecycleDelegate
engine:
engine
1021 receivedConnectNotificationFor:mockScene]);
1024 - (void)testSpawnsShareGpuContext {
1031 XCTAssertNotNil(spawn);
1032 XCTAssertTrue(
engine.platformView !=
nullptr);
1034 std::shared_ptr<flutter::IOSContext> engine_context =
engine.platformView->GetIosContext();
1036 XCTAssertEqual(engine_context, spawn_context);
1039 - (void)testEnableSemanticsWhenFlutterViewAccessibilityDidCall {
1041 engine.ensureSemanticsEnabledCalled = NO;
1042 [engine flutterViewAccessibilityDidCall];
1043 XCTAssertTrue(
engine.ensureSemanticsEnabledCalled);
1046 - (void)testCanMergePlatformAndUIThread {
1047 #if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
1053 XCTAssertEqual(
engine.shell.GetTaskRunners().GetUITaskRunner(),
1054 engine.shell.GetTaskRunners().GetPlatformTaskRunner());
1058 - (void)testAddSceneDelegateToRegistrar {
1061 id mockEngine = OCMPartialMock(
engine);
1062 NSObject<FlutterPluginRegistrar>* registrar = [mockEngine registrarForPlugin:@"plugin"];
1064 [registrar addSceneDelegate:mockPlugin];
1066 OCMVerify(times(1), [mockEngine addSceneLifeCycleDelegate:[OCMArg any]]);
1069 - (void)testNotifyAppDelegateOfEngineInitialization {
1073 id mockApplication = OCMClassMock([UIApplication
class]);
1074 OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1076 OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1078 [engine performImplicitEngineCallback];
1079 OCMVerify(times(1), [mockAppDelegate didInitializeImplicitFlutterEngine:[OCMArg any]]);
1082 - (void)testRegistrarForPlugin {
1090 OCMStub([mockEngine
viewController]).andReturn(mockViewController);
1091 OCMStub([mockEngine binaryMessenger]).andReturn(mockBinaryMessenger);
1092 OCMStub([mockEngine textureRegistry]).andReturn(mockTextureRegistry);
1093 OCMStub([mockEngine platformViewsController]).andReturn(mockPlatformViewController);
1095 NSString* pluginKey =
@"plugin";
1096 NSString* assetKey =
@"asset";
1097 NSString* factoryKey =
@"platform_view_factory";
1099 NSObject<FlutterPluginRegistrar>* registrar = [mockEngine
registrarForPlugin:pluginKey];
1101 XCTAssertTrue([registrar respondsToSelector:
@selector(messenger)]);
1102 XCTAssertTrue([registrar respondsToSelector:
@selector(textures)]);
1103 XCTAssertTrue([registrar respondsToSelector:
@selector(registerViewFactory:withId:)]);
1104 XCTAssertTrue([registrar
1105 respondsToSelector:
@selector(registerViewFactory:withId:gestureRecognizersBlockingPolicy:)]);
1106 XCTAssertTrue([registrar respondsToSelector:
@selector(
viewController)]);
1107 XCTAssertTrue([registrar respondsToSelector:
@selector(publish:)]);
1108 XCTAssertTrue([registrar respondsToSelector:
@selector(valuePublishedByPlugin:)]);
1109 XCTAssertTrue([registrar respondsToSelector:
@selector(addMethodCallDelegate:channel:)]);
1110 XCTAssertTrue([registrar respondsToSelector:
@selector(addApplicationDelegate:)]);
1111 XCTAssertTrue([registrar respondsToSelector:
@selector(lookupKeyForAsset:)]);
1112 XCTAssertTrue([registrar respondsToSelector:
@selector(lookupKeyForAsset:fromPackage:)]);
1115 XCTAssertEqual(registrar.messenger, mockBinaryMessenger);
1116 XCTAssertEqual(registrar.textures, mockTextureRegistry);
1117 XCTAssertEqual(registrar.viewController, mockViewController);
1122 [registrar registerViewFactory:mockPlatformViewFactory withId:factoryKey];
1123 [registrar registerViewFactory:mockPlatformViewFactory
1125 gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager];
1126 OCMVerify(times(2), [mockPlatformViewController registerViewFactory:mockPlatformViewFactory
1128 gestureRecognizersBlockingPolicy:
1133 [registrar publish:plugin];
1137 id published = [registrar valuePublishedByPlugin:pluginKey];
1138 XCTAssertEqual(plugin, published);
1141 [registrar lookupKeyForAsset:assetKey];
1142 OCMVerify(times(1), [mockEngine lookupKeyForAsset:assetKey]);
1143 [registrar lookupKeyForAsset:assetKey fromPackage:pluginKey];
1144 OCMVerify(times(1), [mockEngine lookupKeyForAsset:assetKey fromPackage:pluginKey]);
1147 - (void)testRegistrarForApplication {
1155 OCMStub([mockEngine
viewController]).andReturn(mockViewController);
1156 OCMStub([mockEngine binaryMessenger]).andReturn(mockBinaryMessenger);
1157 OCMStub([mockEngine textureRegistry]).andReturn(mockTextureRegistry);
1158 OCMStub([mockEngine platformViewsController]).andReturn(mockPlatformViewController);
1160 NSString* pluginKey =
@"plugin";
1161 NSString* factoryKey =
@"platform_view_factory";
1163 NSObject<FlutterApplicationRegistrar>* registrar = [mockEngine registrarForApplication:pluginKey];
1165 XCTAssertTrue([registrar respondsToSelector:
@selector(engineIdentifier)]);
1166 XCTAssertEqual(registrar.engineIdentifier,
engine.engineIdentifier);
1167 XCTAssertTrue([registrar respondsToSelector:
@selector(messenger)]);
1168 XCTAssertTrue([registrar respondsToSelector:
@selector(textures)]);
1169 XCTAssertTrue([registrar respondsToSelector:
@selector(registerViewFactory:withId:)]);
1170 XCTAssertTrue([registrar
1171 respondsToSelector:
@selector(registerViewFactory:withId:gestureRecognizersBlockingPolicy:)]);
1172 XCTAssertFalse([registrar respondsToSelector:
@selector(
viewController)]);
1173 XCTAssertFalse([registrar respondsToSelector:
@selector(publish:)]);
1174 XCTAssertFalse([registrar respondsToSelector:
@selector(valuePublishedByPlugin:)]);
1175 XCTAssertFalse([registrar respondsToSelector:
@selector(addMethodCallDelegate:channel:)]);
1176 XCTAssertFalse([registrar respondsToSelector:
@selector(addApplicationDelegate:)]);
1177 XCTAssertFalse([registrar respondsToSelector:
@selector(lookupKeyForAsset:)]);
1178 XCTAssertFalse([registrar respondsToSelector:
@selector(lookupKeyForAsset:fromPackage:)]);
1181 XCTAssertEqual(registrar.messenger, mockBinaryMessenger);
1182 XCTAssertEqual(registrar.textures, mockTextureRegistry);
1187 [registrar registerViewFactory:mockPlatformViewFactory withId:factoryKey];
1188 [registrar registerViewFactory:mockPlatformViewFactory
1190 gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager];
1191 OCMVerify(times(2), [mockPlatformViewController registerViewFactory:mockPlatformViewFactory
1193 gestureRecognizersBlockingPolicy:
1197 - (void)testSendDeepLinkToFrameworkTimesOut {
1200 id mockEngine = OCMPartialMock(
engine);
1201 id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@YES, nil];
1202 OCMStub([mockEngine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]);
1204 NSURL* url = [NSURL URLWithString:@"example.com"];
1206 [mockEngine sendDeepLinkToFramework:url
1207 completionHandler:^(BOOL success) {
1208 XCTAssertFalse(success);
1212 - (void)testSendDeepLinkToFrameworkUsingNavigationChannel {
1213 NSString* urlString =
@"example.com";
1214 NSURL* url = [NSURL URLWithString:urlString];
1217 id mockEngine = OCMPartialMock(
engine);
1218 id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@NO, nil];
1219 OCMStub([mockEngine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]);
1221 OCMStub([mockEngine navigationChannel]).andReturn(mockNavigationChannel);
1222 id mockNavigationChannelCallback = [OCMArg invokeBlockWithArgs:@1, nil];
1223 OCMStub([mockNavigationChannel invokeMethod:
@"pushRouteInformation"
1224 arguments:@{
@"location" : urlString}
1225 result:mockNavigationChannelCallback]);
1227 [mockEngine sendDeepLinkToFramework:url
1228 completionHandler:^(BOOL success) {
1229 XCTAssertTrue(success);
1233 - (void)testSendDeepLinkToFrameworkUsingNavigationChannelFails {
1234 NSString* urlString =
@"example.com";
1235 NSURL* url = [NSURL URLWithString:urlString];
1238 id mockEngine = OCMPartialMock(
engine);
1239 id mockEngineFirstFrameCallback = [OCMArg invokeBlockWithArgs:@NO, nil];
1240 OCMStub([mockEngine waitForFirstFrame:3.0 callback:mockEngineFirstFrameCallback]);
1242 OCMStub([mockEngine navigationChannel]).andReturn(mockNavigationChannel);
1243 id mockNavigationChannelCallback = [OCMArg invokeBlockWithArgs:@0, nil];
1244 OCMStub([mockNavigationChannel invokeMethod:
@"pushRouteInformation"
1245 arguments:@{
@"location" : urlString}
1246 result:mockNavigationChannelCallback]);
1248 [mockEngine sendDeepLinkToFramework:url
1249 completionHandler:^(BOOL success) {
1250 XCTAssertFalse(success);
1254 #pragma mark - Scene Lifecycle Warning Tests
1256 - (void)testAddApplicationDelegateLogsWarningWhenPluginDoesNotConformToSceneDelegate {
1257 FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
1258 writer.expectedOutput =
@"uses deprecated application lifecycle events";
1259 FlutterLogger.outputWriter = writer;
1268 id mockApplication = OCMClassMock([UIApplication
class]);
1269 OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1270 OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1272 [registrar addApplicationDelegate:mockPlugin];
1274 XCTAssertTrue(writer.gotExpectedOutput,
1275 @"Expected warning about plugin not adopting scenes was not logged");
1278 - (void)testAddApplicationDelegateDoesNotLogWarningWhenPluginConformsToSceneDelegate {
1279 FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
1280 FlutterLogger.outputWriter = writer;
1283 id<FlutterPluginRegistrar> registrar = [engine
registrarForPlugin:@"TestPluginWithSceneEvents"];
1288 id mockApplication = OCMClassMock([UIApplication
class]);
1289 OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1290 OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1292 [registrar addApplicationDelegate:mockPlugin];
1294 XCTAssertFalse(writer.didLog,
@"No warning should be logged for scene-conforming plugin");
1297 - (void)testAddApplicationDelegateDoesNotLogWarningWhenPluginDoesNotUseLifecycleEvents {
1298 FlutterStringOutputWriter* writer = [[FlutterStringOutputWriter alloc] init];
1299 FlutterLogger.outputWriter = writer;
1310 id mockApplication = OCMClassMock([UIApplication
class]);
1311 OCMStub([mockApplication sharedApplication]).andReturn(mockApplication);
1312 OCMStub([mockApplication delegate]).andReturn(mockAppDelegate);
1314 [registrar addApplicationDelegate:plugin];
1316 XCTAssertFalse(writer.didLog,
1317 @"No warning should be logged for a plugin that doesn't use lifecycle events");
NS_ASSUME_NONNULL_BEGIN typedef void(^ FlutterBinaryReply)(NSData *_Nullable reply)
int64_t FlutterBinaryMessengerConnection
flutter::Settings FLTDefaultSettingsForBundle(NSBundle *bundle, NSProcessInfo *processInfoOrNil)
@ FlutterPlatformViewGestureRecognizersBlockingPolicyEager
FlutterViewController * viewController
BOOL runWithEntrypoint:initialRoute:(nullable NSString *entrypoint,[initialRoute] nullable NSString *NS_SWIFT_UI_ACTOR)
flutter::PlatformViewIOS * platformView()
void setBinaryMessenger:(FlutterBinaryMessengerRelay *binaryMessenger)
FlutterEngine * spawnWithEntrypoint:libraryURI:initialRoute:entrypointArgs:(/*nullable */NSString *entrypoint,[libraryURI]/*nullable */NSString *libraryURI,[initialRoute]/*nullable */NSString *initialRoute,[entrypointArgs]/*nullable */NSArray< NSString * > *NS_SWIFT_UI_ACTOR)
NSMutableDictionary * pluginPublications
void ensureSemanticsEnabled()
void waitForFirstFrame:callback:(NSTimeInterval timeout,[callback] void(^ callback)(BOOL didTimeout))
instancetype methodCallWithMethodName:arguments:(NSString *method,[arguments] id _Nullable arguments)
UIApplication * application
A FlutterTexture that vends no frames. Used to obtain a registered texture id.
id CreateMockViewControllerOnScreen(CGSize screenNativeSize, CGFloat screenScale)
nullable NSObject< FlutterPluginRegistrar > * registrarForPlugin:(NSString *pluginKey)
CVPixelBufferRef _Nullable copyPixelBuffer()