Repository navigation
[image_picker] Add native tests for pick results, camera access, and presentation - #12539
Conversation
There was a problem hiding this comment.
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.
| 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); | ||
| } |
There was a problem hiding this comment.
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);
}There was a problem hiding this comment.
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.
| 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]; |
There was a problem hiding this comment.
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.
| 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]; |
There was a problem hiding this comment.
Agreed and fixed. The window is now created with initWithFrame: so the test doesn’t depend on an active UIWindowScene.
| 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]; |
There was a problem hiding this comment.
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.
| 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]; |
There was a problem hiding this comment.
Agreed and fixed. initWithFrame: already leaves windowScene nil, so this covers the frame fallback without a partial mock.
| plugin.callContext = [[FLTImagePickerMethodCallContext alloc] | ||
| initWithResult:^(NSArray<NSString *> *result, FlutterError *error) { | ||
| XCTAssertEqual(result.count, 1); | ||
| XCTAssertNil(error); |
There was a problem hiding this comment.
we should probably validate that the imageQuality is actually clamped here, right now were just testing that the method doesnt crash
There was a problem hiding this comment.
Agreed. These were going through PHPicker with a PNG, so they couldn’t observe quality at all. The test now calls getDesiredImageQuality: directly and asserts that -1 is clamped to 1.0
| plugin.callContext = [[FLTImagePickerMethodCallContext alloc] | ||
| initWithResult:^(NSArray<NSString *> *result, FlutterError *error) { | ||
| XCTAssertEqual(result.count, 1); | ||
| XCTAssertNil(error); |
There was a problem hiding this comment.
similar to the previous test, we should probably validate that imageQuality actually scaled
There was a problem hiding this comment.
Agreed. This now asserts that 50 is scaled to 0.5
| plugin.callContext = [[FLTImagePickerMethodCallContext alloc] | ||
| initWithResult:^(NSArray<NSString *> *result, FlutterError *error) { | ||
| XCTAssertEqual(result.count, 1); | ||
| [resultExpectation fulfill]; |
There was a problem hiding this comment.
Agreed. This now asserts that 150 is clamped to 1.0
| quality:nil | ||
| fullMetadata:YES | ||
| completion:^(NSString *result, FlutterError *error) { | ||
| XCTAssertNil(result); |
There was a problem hiding this comment.
missing an assert on the error here
There was a problem hiding this comment.
Agreed. Added XCTAssertNil(error). Unavailable camera completes with a nil path list and no error
e4f1da4 to
865c506
Compare
…and presentation.
…ontroller for alert presentation
…siredImageQuality method and simplify test cases
865c506 to
267cee7
Compare
|
From triage: Please rebase off main so that tests will pass |
This is already rebased onto main and the comments have been addressed. It needs to land first so that #12540 can then be rebased onto main, that PR is stacked on this one. |
|
auto label is removed for flutter/packages/12539, Failed to merge flutter/packages/12539 with Pull request flutter/packages/12539 could not be merged: Merging stacked PRs via this endpoint is not supported. Use the asynchronous merge endpoint instead.. |
…presentation (flutter#12539) 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 **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). 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. [^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.
…icker completion (#12540) Stacked on #12539. Adds native unit tests for previously untested paths in `FLTImagePickerPlugin.m` (photo-library authorization, `UIImagePicker` launch, and `didFinishPickingMediaWithInfo:`) before the Objective-C → Swift migration. Production code is unchanged. This is a tests-only change, so it does not bump the package version or CHANGELOG. `ImagePickerPluginTests` go from 52 tests to 70 tests (+18). ### New test cases **Photo-library access:** - `testLaunchUIImagePickerGalleryWithoutFullMetadataSkipsAuthorization` — gallery without full metadata skips the authorization check - `testPhotoAccessDeniedReturnsError` — denied photo access returns an error - `testPhotoAccessRestrictedReturnsError` — restricted photo access returns an error - `testPhotoAccessAuthorizedShowsLibrary` — authorized access presents the library - `testPhotoAccessNotDeterminedGrantedShowsLibrary` — prompt granted presents the library - `testPhotoAccessNotDeterminedDeniedReturnsError` — prompt denied returns an error - `testPhotoAccessLimitedReturnsDeniedError` — Limited access falls through to denied - `testPhotoAccessUnknownStatusTreatedAsDenied` — unknown status is treated as denied **`launchUIImagePickerWithSource:`:** - `testLaunchUIImagePickerInvalidSourceReturnsError` — an invalid source returns an error - `testLaunchUIImagePickerSetsImageAndVideoMediaTypes` — image/video media types and duration are set on the picker **`imagePickerController:didFinishPickingMediaWithInfo:`:** - `testImagePickerDidFinishPickingOriginalImage` — original image is saved - `testImagePickerDidFinishPickingPrefersEditedImage` — edited image is preferred over original - `testImagePickerDidFinishPickingScalesImage` — the image is scaled when requested - `testImagePickerDidFinishPickingWithFullMetadataAsset` — full-metadata path uses `PHImageManager` when an asset is present - `testImagePickerDidFinishPickingFullMetadataWithoutAsset` — full metadata without an asset still completes - `testImagePickerDidFinishPickingVideo` — video is copied successfully - `testImagePickerDidFinishPickingVideoCopyFailure` — a video copy failure is reported - `testImagePickerDidFinishPickingIgnoredWhenNoCallContext` — no `callContext` is a no-op Third part of `image_picker_ios` coverage backfill before the Obj-C → Swift migration for flutter/flutter#119107 ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). 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. [^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.
…er#192550) flutter/packages@36e088a...8a35b16 2026-09-10 [email protected] [material_ui] Migrate M3 buttons template to use new gen_defaults (flutter/packages#12744) 2026-09-09 [email protected] [cupertino_ui]Add awaitNotRequired to Future-returning callsites without await (flutter/packages#12817) 2026-09-09 [email protected] [material_ui] Add awaitNotRequired annotation to material_ui (flutter/packages#12622) 2026-09-09 [email protected] [image_picker] Add native tests for photo-library access and UIImagePicker completion (flutter/packages#12540) 2026-09-09 [email protected] [material_ui][cupertino_ui] allow page routes to opt out of route semantics - flutter#182556 (flutter/packages#12674) 2026-09-09 [email protected] [image_picker] Add native tests for pick results, camera access, and presentation (flutter/packages#12539) 2026-09-09 [email protected] [cupertino_ui] Fix platform view sheet transitions (flutter/packages#12565) 2026-09-09 [email protected] [camera_android_camerax] Bump cameraxVersion to 1.6.2, remove concurrent-futures workaround (flutter/packages#12698) 2026-09-09 [email protected] `[material_ui]` replace identical checks with equality when dealing with enums (flutter/packages#12633) 2026-09-09 [email protected] Roll Flutter from b444e78 to 63b9518 (21 revisions) (flutter/packages#12814) 2026-09-09 [email protected] `[cupertino_ui]` replace identical checks with equality when dealing with enums (flutter/packages#12632) 2026-09-09 [email protected] [pigeon] add support for multiple swift outputs (flutter/packages#12720) If this roll has caused a breakage, revert this CL and set the roller to dry run mode using the controls here: https://autoroll.skia.org/r/flutter-packages-flutter-autoroll Please CC [email protected] on the revert to ensure that a human is aware of the problem. To file a bug in Flutter: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md
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 existingStubViewProvider/ OCMock conventions inImagePickerPluginTests.m.This is a tests-only change, so it does not bump the package version or CHANGELOG.
ImagePickerPluginTestsgo from 33 tests to 52 tests (+19).New test cases
Pick results / dismiss:
testPickImageInvalidResultWhenMultiplePathsReturned— image pick with multiple paths uses the existinginvalid_resultdouble-completion behaviortestPickVideoInvalidResultWhenMultiplePathsReturned— same for video picktestPHPickerCancelSendsEmptyPathList— PHPicker cancel completes with an empty path listtestPresentationControllerDidDismissSendsEmptyPathList— dismiss completes with an empty path listImage quality:
testDesiredImageQualityClampsOutOfRangeValues— quality below 0 is clampedtestDesiredImageQualityScalesValidPercent— a valid percent is scaledtestDesiredImageQualityOver100IsClamped— quality above 100 is clampedCamera access:
testCameraAccessDeniedReturnsError— denied authorization returns an errortestCameraAccessRestrictedReturnsError— restricted authorization returns an errortestCameraAccessNotDeterminedDenied— prompt denied returns an errortestCameraAccessNotDeterminedGrantedPresentsCamera— prompt granted presents the cameratestCameraAccessUnknownStatusTreatedAsDenied— unknown status is treated as deniedtestShowCameraWhenUnavailableSendsNilPathList— unavailable camera completes with a nil path listtestShowCameraReturnsEarlyWhenAlreadyBeingPresented— a second present is a no-optestShowCameraUnavailableAlertOKHandler— the unavailable-camera alert OK handler runsPresentation / blocker window:
testPresentingViewControllerWithoutWindowReturnsHostController— no window returns the host view controllertestPresentingViewControllerReusesExistingBlockerWindow— an existing interaction-blocker window is reusedtestPresentingViewControllerWithoutWindowSceneUsesFrame— missing window scene falls back to a frametestDefaultViewProviderReturnsRegistrarViewController— the default view provider returns the registrar’s view controllerSecond part of
image_picker_ioscoverage backfill before the Obj-C → Swift migration for flutter/flutter#119107Pre-Review Checklist
[shared_preferences]///).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-assistbot 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
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