Skip to content

[image_picker] Add native tests for pick results, camera access, and presentation - #12539

Open
victogomez-cs wants to merge 2 commits into
mainfrom
image_picker_coverage_2_camera_and_results
Open

[image_picker] Add native tests for pick results, camera access, and presentation#12539
victogomez-cs wants to merge 2 commits into
mainfrom
image_picker_coverage_2_camera_and_results

Conversation

@victogomez-cs

Copy link
Copy Markdown

Adds native unit tests for previously untested paths in FLTImagePickerPlugin.m (pick-result handling, camera authorization, and presentation) before the Objective-C → Swift migration. Production code is unchanged. New cases follow the existing StubViewProvider / OCMock conventions in ImagePickerPluginTests.m.

This is a tests-only change, so it does not bump the package version or CHANGELOG.

ImagePickerPluginTests go from 33 tests to 52 tests (+19).

New test cases

Pick results / dismiss:

  • testPickImageInvalidResultWhenMultiplePathsReturned — image pick with multiple paths uses the existing invalid_result double-completion behavior
  • testPickVideoInvalidResultWhenMultiplePathsReturned — same for video pick
  • testPHPickerCancelSendsEmptyPathList — PHPicker cancel completes with an empty path list
  • testPresentationControllerDidDismissSendsEmptyPathList — dismiss completes with an empty path list

Image quality:

  • testDesiredImageQualityClampsOutOfRangeValues — quality below 0 is clamped
  • testDesiredImageQualityScalesValidPercent — a valid percent is scaled
  • testDesiredImageQualityOver100IsClamped — quality above 100 is clamped

Camera access:

  • testCameraAccessDeniedReturnsError — denied authorization returns an error
  • testCameraAccessRestrictedReturnsError — restricted authorization returns an error
  • testCameraAccessNotDeterminedDenied — prompt denied returns an error
  • testCameraAccessNotDeterminedGrantedPresentsCamera — prompt granted presents the camera
  • testCameraAccessUnknownStatusTreatedAsDenied — unknown status is treated as denied
  • testShowCameraWhenUnavailableSendsNilPathList — unavailable camera completes with a nil path list
  • testShowCameraReturnsEarlyWhenAlreadyBeingPresented — a second present is a no-op
  • testShowCameraUnavailableAlertOKHandler — the unavailable-camera alert OK handler runs

Presentation / blocker window:

  • testPresentingViewControllerWithoutWindowReturnsHostController — no window returns the host view controller
  • testPresentingViewControllerReusesExistingBlockerWindow — an existing interaction-blocker window is reused
  • testPresentingViewControllerWithoutWindowSceneUsesFrame — missing window scene falls back to a frame
  • testDefaultViewProviderReturnsRegistrarViewController — the default view provider returns the registrar’s view controller

Second part of image_picker_ios coverage backfill before the Obj-C → Swift migration for flutter/flutter#119107

Pre-Review Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the gemini-code-assist bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

Footnotes

  1. Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. 2

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds comprehensive unit tests to ImagePickerPluginTests.m covering image and video picking results, camera access permissions, image quality clamping, and view controller presentation. The review feedback suggests refactoring several tests to avoid relying on UIApplication.sharedApplication.connectedScenes and real UIWindow instances, recommending instead the use of mock view controllers or initializing UIWindow with a simple frame to ensure tests are robust and run reliably in headless environments.

Comment on lines +1147 to +1177
UIWindowScene *scene =
(UIWindowScene *)UIApplication.sharedApplication.connectedScenes.allObjects.firstObject;
UIWindow *window = [[UIWindow alloc] initWithWindowScene:scene];
window.frame = scene.coordinateSpace.bounds;
UIViewController *rootViewController = [[UIViewController alloc] init];
window.rootViewController = rootViewController;
[rootViewController loadViewIfNeeded];
[window makeKeyAndVisible];

FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc]
initWithViewProvider:[[StubViewProvider alloc] initWithViewController:rootViewController]];
[plugin setImagePickerControllerOverrides:@[ [[UIImagePickerController alloc] init] ]];

XCTestExpectation *resultExpectation = [self expectationWithDescription:@"unavailable"];
[plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera
camera:FLTSourceCameraRear]
maxSize:[[FLTMaxSize alloc] init]
quality:nil
fullMetadata:YES
completion:^(NSString *result, FlutterError *error) {
XCTAssertNil(result);
[resultExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:30 handler:nil];

UIAlertController *alert = (UIAlertController *)rootViewController.presentedViewController;
XCTAssertTrue([alert isKindOfClass:[UIAlertController class]]);
void (^handler)(UIAlertAction *) = [alert.actions.firstObject valueForKey:@"handler"];
if (handler) {
handler(alert.actions.firstObject);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Relying on UIApplication.sharedApplication.connectedScenes and creating/making key a real UIWindow is fragile, slow, and will fail in headless environments or logic tests where no active scene or host application window exists. Instead, you can use a mock UIViewController to capture and verify the presented UIAlertController and its action handler directly. This is faster, more robust, and completely independent of the window hierarchy.

  id mockViewController = OCMClassMock([UIViewController class]);
  __block UIAlertController *alert = nil;
  OCMStub([mockViewController presentViewController:[OCMArg any] animated:YES completion:nil])
      .andDo(^(NSInvocation *invocation) {
        [invocation getArgument:&alert atIndex:2];
      });

  FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc]
      initWithViewProvider:[[StubViewProvider alloc] initWithViewController:mockViewController]];
  [plugin setImagePickerControllerOverrides:@[ [[UIImagePickerController alloc] init] ]];

  XCTestExpectation *resultExpectation = [self expectationWithDescription:@"unavailable"];
  [plugin pickImageWithSource:[FLTSourceSpecification makeWithType:FLTSourceTypeCamera
                                                            camera:FLTSourceCameraRear]
                      maxSize:[[FLTMaxSize alloc] init]
                      quality:nil
                 fullMetadata:YES
                   completion:^(NSString *result, FlutterError *error) {
                     XCTAssertNil(result);
                     [resultExpectation fulfill];
                   }];
  [self waitForExpectationsWithTimeout:30 handler:nil];

  XCTAssertTrue([alert isKindOfClass:[UIAlertController class]]);
  void (^handler)(UIAlertAction *) = [alert.actions.firstObject valueForKey:@"handler"];
  if (handler) {
    handler(alert.actions.firstObject);
  }

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed. This test now uses an OCMock UIViewController to capture the presented UIAlertController instead of creating a real key window from UIApplication.sharedApplication.connectedScenes.

Comment on lines +1189 to +1196
UIWindowScene *scene =
(UIWindowScene *)UIApplication.sharedApplication.connectedScenes.allObjects.firstObject;
UIWindow *window = [[UIWindow alloc] initWithWindowScene:scene];
window.frame = scene.coordinateSpace.bounds;
UIViewController *rootViewController = [[UIViewController alloc] init];
window.rootViewController = rootViewController;
[rootViewController loadViewIfNeeded];
[window makeKeyAndVisible];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using UIApplication.sharedApplication.connectedScenes to initialize the UIWindow is fragile and will fail in headless environments or logic tests where connectedScenes is empty. You can initialize the UIWindow with a simple frame instead, which is fully supported and doesn't rely on active scenes or host application state.

Suggested change
UIWindowScene *scene =
(UIWindowScene *)UIApplication.sharedApplication.connectedScenes.allObjects.firstObject;
UIWindow *window = [[UIWindow alloc] initWithWindowScene:scene];
window.frame = scene.coordinateSpace.bounds;
UIViewController *rootViewController = [[UIViewController alloc] init];
window.rootViewController = rootViewController;
[rootViewController loadViewIfNeeded];
[window makeKeyAndVisible];
UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UIViewController *rootViewController = [[UIViewController alloc] init];
window.rootViewController = rootViewController;
[rootViewController loadViewIfNeeded];

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed. The window is now created with initWithFrame: so the test doesn’t depend on an active UIWindowScene.

Comment on lines +1207 to +1223
UIWindowScene *scene =
(UIWindowScene *)UIApplication.sharedApplication.connectedScenes.allObjects.firstObject;
UIWindow *window = [[UIWindow alloc] initWithWindowScene:scene];
window.frame = scene.coordinateSpace.bounds;
UIViewController *rootViewController = [[UIViewController alloc] init];
window.rootViewController = rootViewController;
[rootViewController loadViewIfNeeded];
[window makeKeyAndVisible];

id mockWindow = OCMPartialMock(window);
OCMStub([mockWindow windowScene]).andReturn(nil);

FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc]
initWithViewProvider:[[StubViewProvider alloc] initWithViewController:rootViewController]];
XCTAssertNotNil([plugin presentingViewControllerForImagePickerInNewWindow]);
[plugin removeInteractionBlocker];
[mockWindow stopMocking];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

By initializing the UIWindow with initWithFrame:, the window's windowScene is nil by default on iOS 13+. This allows you to test the fallback frame path directly without needing to query connectedScenes, instantiate a scene, or use OCMPartialMock to stub windowScene to return nil.

Suggested change
UIWindowScene *scene =
(UIWindowScene *)UIApplication.sharedApplication.connectedScenes.allObjects.firstObject;
UIWindow *window = [[UIWindow alloc] initWithWindowScene:scene];
window.frame = scene.coordinateSpace.bounds;
UIViewController *rootViewController = [[UIViewController alloc] init];
window.rootViewController = rootViewController;
[rootViewController loadViewIfNeeded];
[window makeKeyAndVisible];
id mockWindow = OCMPartialMock(window);
OCMStub([mockWindow windowScene]).andReturn(nil);
FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc]
initWithViewProvider:[[StubViewProvider alloc] initWithViewController:rootViewController]];
XCTAssertNotNil([plugin presentingViewControllerForImagePickerInNewWindow]);
[plugin removeInteractionBlocker];
[mockWindow stopMocking];
UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UIViewController *rootViewController = [[UIViewController alloc] init];
window.rootViewController = rootViewController;
[rootViewController loadViewIfNeeded];
FLTImagePickerPlugin *plugin = [[FLTImagePickerPlugin alloc]
initWithViewProvider:[[StubViewProvider alloc] initWithViewController:rootViewController]];
XCTAssertNotNil([plugin presentingViewControllerForImagePickerInNewWindow]);
[plugin removeInteractionBlocker];

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and fixed. initWithFrame: already leaves windowScene nil, so this covers the frame fallback without a partial mock.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant