Skip to content

Commit 5db6716

Browse files
[google_sign_in] Increase iOS coverage tests (flutter#12484)
Adds native unit tests for previously untested paths in `FLTGoogleSignInPlugin.m` 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. Native unit tests go from 21 tests / 6 suites to 31 tests / 11 suites. ### New test cases **`urlHandling` (iOS / Mac Catalyst only)** — these APIs do not exist on macOS (`handleOpenURLs:` is the macOS path): - `applicationOpenURL` — `application:openURL:options:` forwards the URL to GID and returns `true` - `applicationOpenURLReturnsHandleResult` — same path returns `false` when GID does - `sceneOpenURLContexts` — `scene:openURLContexts:` forwards the URL from a `UIOpenURLContext` stand-in **`errorMapping`:** - `mapsRemainingGIDSignInErrorCodes` (parameterized): - `GIDSignInError.keychain` → `FSIGoogleSignInErrorCode.keychainError` - `GIDSignInError.EMM` → `FSIGoogleSignInErrorCode.eemError` - `GIDSignInError.unknown` → `FSIGoogleSignInErrorCode.unknown` - unrecognized SDK code (`12345`) → `FSIGoogleSignInErrorCode.unknown` - `sanitizesComplexUserInfoInFlutterError` — `FSISanitizedUserInfo` keeps strings/numbers/URLs/arrays/dicts/nested errors and stringifies unsupported types (e.g. `Date`) **`disconnect`:** - `disconnectReturnsFlutterErrorOnFailure` — a GID disconnect failure is returned as a Flutter error with domain/code and userInfo **`userData`:** - `signInWithoutProfileImageOmitsPhotoUrl` — a user with no profile photo gets `photoUrl == nil` and still maps `displayName` **`topViewController` (iOS / Mac Catalyst only)** — macOS presents with `NSWindow`, not a `UIViewController` hierarchy: - `usesNavigationControllerVisibleController` — presents from the nav stack’s top VC - `usesTabBarControllerSelectedController` — presents from the selected tab VC - `usesPresentedViewController` — presents from a presented VC Also records URLs passed to `TestSignIn.handle(_:)` so the URL-handling cases can assert the fake was called. First part of Swift migration to backfill code coverage for flutter#119103 ## Pre-Review Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] page, which explains my responsibilities. - [x] I read and followed the [relevant style guides] and ran [the auto-formatter]. - [x] I signed the [CLA]. - [x] The title of the PR starts with the name of the package surrounded by square brackets, e.g. `[shared_preferences]` - [x] I [linked to at least one issue that this PR fixes] in the description above. - [x] I followed [the version and CHANGELOG instructions], using [semantic versioning] and the [repository CHANGELOG style], or I have commented below to indicate which documented exception this PR falls under[^1]. - [x] I updated/added any relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or I have commented below to indicate which [test exemption] this PR falls under[^1]. - [x] All existing and new tests are passing. 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](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. <!-- Links --> [Contributor Guide]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md [relevant style guides]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md#style [the auto-formatter]: https://github.com/flutter/packages/blob/main/script/tool/README.md#format-code [CLA]: https://cla.developers.google.com/ [Discord]: https://github.com/flutter/flutter/blob/master/docs/contributing/Chat.md [linked to at least one issue that this PR fixes]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#overview [the version and CHANGELOG instructions]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#version-and-changelog-updates [semantic versioning]: https://dart.dev/tools/pub/versioning#semantic-versions [repository CHANGELOG style]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#changelog-style [test exemption]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#tests
1 parent 90ba788 commit 5db6716

6 files changed

Lines changed: 255 additions & 5 deletions

File tree

‎packages/google_sign_in/google_sign_in_ios/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 6.3.1
2+
3+
* Improves testability of iOS scene URL handling.
4+
15
## 6.3.0
26

37
* Adds UIScene compatibility.

‎packages/google_sign_in/google_sign_in_ios/darwin/Tests/GoogleSignInTests.swift‎

Lines changed: 226 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,13 @@ class TestSignIn: NSObject, FSIGIDSignIn {
4949
// Whether signOut was called.
5050
var signOutCalled = false
5151

52+
// URLs passed to handleURL:, and the value to return.
53+
var handledURLs: [URL] = []
54+
var handleURLResult = true
55+
5256
func handle(_ url: URL) -> Bool {
53-
return true
57+
handledURLs.append(url)
58+
return handleURLResult
5459
}
5560

5661
func restorePreviousSignIn(completion: (((any FSIGIDGoogleUser)?, Error?) -> Void)?) {
@@ -693,8 +698,228 @@ struct GoogleSignInPluginTests {
693698
}
694699
}
695700
}
701+
702+
@Suite("urlHandling")
703+
@MainActor
704+
struct URLHandlingTests {
705+
#if os(iOS) || targetEnvironment(macCatalyst)
706+
@Test func applicationOpenURL() {
707+
let (plugin, fakeSignIn) = createTestPlugin()
708+
let url = URL(string: "com.googleusercontent.apps.test:/oauthredirect")!
709+
fakeSignIn.handleURLResult = true
710+
711+
let handled = plugin.application(UIApplication.shared, open: url, options: [:])
712+
713+
#expect(handled == true)
714+
#expect(fakeSignIn.handledURLs == [url])
715+
}
716+
717+
@Test func applicationOpenURLReturnsHandleResult() {
718+
let (plugin, fakeSignIn) = createTestPlugin()
719+
let url = URL(string: "com.googleusercontent.apps.test:/oauthredirect")!
720+
fakeSignIn.handleURLResult = false
721+
722+
let handled = plugin.application(UIApplication.shared, open: url, options: [:])
723+
724+
#expect(handled == false)
725+
#expect(fakeSignIn.handledURLs == [url])
726+
}
727+
728+
@Test func handleURLs() {
729+
let (plugin, fakeSignIn) = createTestPlugin()
730+
let firstURL = URL(string: "com.googleusercontent.apps.test:/oauthredirect")!
731+
let secondURL = URL(string: "com.googleusercontent.apps.test:/another")!
732+
733+
plugin.handleURLs([firstURL, secondURL])
734+
735+
#expect(fakeSignIn.handledURLs == [firstURL, secondURL])
736+
}
737+
#endif
738+
}
739+
740+
@Suite("errorMapping") struct ErrorMappingTests {
741+
@Test(arguments: [
742+
(GIDSignInError.keychain.rawValue, FSIGoogleSignInErrorCode.keychainError),
743+
(GIDSignInError.EMM.rawValue, FSIGoogleSignInErrorCode.eemError),
744+
(GIDSignInError.unknown.rawValue, FSIGoogleSignInErrorCode.unknown),
745+
// Unrecognized SDK codes fall through to the default → unknown.
746+
(12_345, FSIGoogleSignInErrorCode.unknown),
747+
]) func mapsRemainingGIDSignInErrorCodes(
748+
signInSDKErrorCode: Int,
749+
expectedPigeonErrorCode: FSIGoogleSignInErrorCode
750+
) async {
751+
let (plugin, fakeSignIn) = createTestPlugin()
752+
fakeSignIn.error = NSError(
753+
domain: kGIDSignInErrorDomain, code: signInSDKErrorCode, userInfo: nil)
754+
755+
await confirmation("completion called") { confirmed in
756+
plugin.signIn(withScopeHint: [], nonce: nil) { result, error in
757+
#expect(error == nil)
758+
#expect(result?.success == nil)
759+
#expect(result?.error?.type == expectedPigeonErrorCode)
760+
confirmed()
761+
}
762+
}
763+
}
764+
765+
@Test func sanitizesComplexUserInfoInFlutterError() async {
766+
let (plugin, _) = createTestPlugin()
767+
let fakeUser = addSignedInUser(to: plugin)
768+
let nested = NSError(domain: "NestedDomain", code: 99, userInfo: ["nestedKey": "nestedValue"])
769+
let userInfo: [String: Any] = [
770+
"string": "ok",
771+
"number": NSNumber(value: 42),
772+
"url": URL(string: "https://example.com/path")!,
773+
"array": ["a", NSNumber(value: 1)],
774+
"dict": ["inner": "value"],
775+
NSUnderlyingErrorKey: nested,
776+
"unsupported": Date(timeIntervalSince1970: 0),
777+
]
778+
fakeUser.error = NSError(domain: "BogusDomain", code: 7, userInfo: userInfo)
779+
780+
await confirmation("completion called") { confirmed in
781+
plugin.refreshedAuthorizationTokens(forUser: fakeUser.userID!) { result, error in
782+
#expect(result == nil)
783+
#expect(error?.code == "BogusDomain: 7")
784+
let details = error?.details as? [String: Any]
785+
#expect(details?["string"] as? String == "ok")
786+
#expect(details?["number"] as? NSNumber == NSNumber(value: 42))
787+
#expect(details?["url"] as? String == "https://example.com/path")
788+
#expect((details?["array"] as? [Any])?.count == 2)
789+
#expect((details?["dict"] as? [String: Any])?["inner"] as? String == "value")
790+
let nestedDetails = details?[NSUnderlyingErrorKey] as? [String: Any]
791+
#expect(nestedDetails?["domain"] as? String == "NestedDomain")
792+
#expect(nestedDetails?["code"] as? String == "99")
793+
let unsupported = details?["unsupported"] as? String
794+
#expect(unsupported?.contains("Unsupported type:") == true)
795+
confirmed()
796+
}
797+
}
798+
}
799+
}
800+
801+
@Suite("disconnect") struct DisconnectTests {
802+
@Test func disconnectReturnsFlutterErrorOnFailure() async {
803+
let (plugin, fakeSignIn) = createTestPlugin()
804+
fakeSignIn.error = NSError(
805+
domain: "DisconnectDomain", code: 3, userInfo: ["reason": "failed"])
806+
807+
await confirmation("completion called") { confirmed in
808+
plugin.disconnect { error in
809+
#expect(error?.code == "DisconnectDomain: 3")
810+
#expect((error?.details as? [String: Any])?["reason"] as? String == "failed")
811+
confirmed()
812+
}
813+
}
814+
}
815+
}
816+
817+
@Suite("userData") struct UserDataTests {
818+
@Test func signInWithoutProfileImageOmitsPhotoUrl() async {
819+
let (plugin, fakeSignIn) = createTestPlugin()
820+
let fakeUser = TestGoogleUser("mockID")
821+
fakeUser.profile = TestProfileData(name: "Name", email: "[email protected]", imageURL: nil)
822+
fakeSignIn.signInResult = TestSignInResult(user: fakeUser)
823+
824+
await confirmation("completion called") { confirmed in
825+
plugin.signIn(withScopeHint: [], nonce: nil) { result, error in
826+
#expect(error == nil)
827+
#expect(result?.success?.user.photoUrl == nil)
828+
#expect(result?.success?.user.displayName == "Name")
829+
confirmed()
830+
}
831+
}
832+
}
833+
}
834+
835+
#if os(iOS) || targetEnvironment(macCatalyst)
836+
@Suite("topViewController")
837+
@MainActor
838+
struct TopViewControllerTests {
839+
@Test func usesNavigationControllerVisibleController() async {
840+
let root = UIViewController()
841+
let nav = UINavigationController(rootViewController: root)
842+
let top = UIViewController()
843+
nav.pushViewController(top, animated: false)
844+
845+
let viewProvider = TestViewProvider()
846+
viewProvider.viewController = nav
847+
let (plugin, fakeSignIn) = createTestPlugin(viewProvider: viewProvider)
848+
fakeSignIn.signInResult = TestSignInResult(user: TestGoogleUser("id"))
849+
850+
await confirmation("completion called") { confirmed in
851+
plugin.signIn(withScopeHint: [], nonce: nil) { _, _ in confirmed() }
852+
}
853+
#expect(fakeSignIn.presentingViewController === top)
854+
}
855+
856+
@Test func usesTabBarControllerSelectedController() async {
857+
let selected = UIViewController()
858+
let other = UIViewController()
859+
let tab = UITabBarController()
860+
tab.viewControllers = [selected, other]
861+
tab.selectedViewController = selected
862+
863+
let viewProvider = TestViewProvider()
864+
viewProvider.viewController = tab
865+
let (plugin, fakeSignIn) = createTestPlugin(viewProvider: viewProvider)
866+
fakeSignIn.signInResult = TestSignInResult(user: TestGoogleUser("id"))
867+
868+
await confirmation("completion called") { confirmed in
869+
plugin.signIn(withScopeHint: [], nonce: nil) { _, _ in confirmed() }
870+
}
871+
#expect(fakeSignIn.presentingViewController === selected)
872+
}
873+
874+
@Test func usesPresentedViewController() async {
875+
let presented = UIViewController()
876+
let host = StubHostingViewController(presented: presented)
877+
878+
let viewProvider = TestViewProvider()
879+
viewProvider.viewController = host
880+
let (plugin, fakeSignIn) = createTestPlugin(viewProvider: viewProvider)
881+
fakeSignIn.signInResult = TestSignInResult(user: TestGoogleUser("id"))
882+
883+
await confirmation("completion called") { confirmed in
884+
plugin.signIn(withScopeHint: [], nonce: nil) { _, _ in confirmed() }
885+
}
886+
#expect(fakeSignIn.presentingViewController === presented)
887+
}
888+
}
889+
#endif
696890
}
697891

892+
#if os(iOS) || targetEnvironment(macCatalyst)
893+
/// Stand-in for UIOpenURLContext that only needs to respond to `URL`.
894+
final class FakeOpenURLContext: NSObject {
895+
@objc(URL) var openURL: URL
896+
897+
init(url: URL) {
898+
self.openURL = url
899+
super.init()
900+
}
901+
}
902+
903+
/// Lets tests stub `presentedViewController` without a real window presentation.
904+
@MainActor
905+
final class StubHostingViewController: UIViewController {
906+
private let stubPresented: UIViewController?
907+
908+
init(presented: UIViewController?) {
909+
self.stubPresented = presented
910+
super.init(nibName: nil, bundle: nil)
911+
}
912+
913+
required init?(coder: NSCoder) {
914+
fatalError("init(coder:) has not been implemented")
915+
}
916+
917+
override var presentedViewController: UIViewController? {
918+
stubPresented
919+
}
920+
}
921+
#endif
922+
698923
func loadGoogleServiceInfo() -> [String: Any]? {
699924
if let plistPath = Bundle(for: TestSignIn.self).path(
700925
forResource: "GoogleService-Info", ofType: "plist")

‎packages/google_sign_in/google_sign_in_ios/darwin/google_sign_in_ios/Sources/google_sign_in_ios/FLTGoogleSignInPlugin.m‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,11 +156,18 @@ - (instancetype)initWithSignIn:(NSObject<FSIGIDSignIn> *)signIn
156156

157157
#if TARGET_OS_IOS
158158

159+
- (void)handleURLs:(NSArray<NSURL *> *)urls {
160+
for (NSURL *url in urls) {
161+
[self.signIn handleURL:url];
162+
}
163+
}
164+
159165
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
166+
NSMutableArray<NSURL *> *urls = [NSMutableArray arrayWithCapacity:URLContexts.count];
160167
for (UIOpenURLContext *context in URLContexts) {
161-
NSURL *url = context.URL;
162-
[self.signIn handleURL:url];
168+
[urls addObject:context.URL];
163169
}
170+
[self handleURLs:urls];
164171
}
165172

166173
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {

‎packages/google_sign_in/google_sign_in_ios/darwin/google_sign_in_ios/Sources/google_sign_in_ios/include/google_sign_in_ios/FLTGoogleSignInPlugin_Test.h‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ NS_ASSUME_NONNULL_BEGIN
3737
googleServiceProperties:(nullable NSDictionary<NSString *, id> *)googleServiceProperties
3838
NS_DESIGNATED_INITIALIZER;
3939

40+
#if TARGET_OS_IOS
41+
/// Forwards each URL to GIDSignIn. Extracted so tests can cover scene URL
42+
/// handling without constructing UIOpenURLContext.
43+
- (void)handleURLs:(NSArray<NSURL *> *)urls NS_SWIFT_NAME(handleURLs(_:));
44+
#endif
45+
4046
@end
4147

4248
NS_ASSUME_NONNULL_END

‎packages/google_sign_in/google_sign_in_ios/example/ios/RunnerUITests/GoogleSignInUITests.m‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,15 @@ - (void)allowSignInPermissions {
3838
[[XCUIApplication alloc] initWithBundleIdentifier:@"com.apple.springboard"];
3939
XCUIElement *permissionAlert = springboard.alerts.firstMatch;
4040
if ([permissionAlert waitForExistenceWithTimeout:5.0]) {
41-
[permissionAlert.buttons[@"Continue"] tap];
41+
// The alert is titled in the simulator's language, so the confirmation
42+
// button can't be looked up by name. It is the last of the alert's two
43+
// buttons ("Cancel" and "Continue") in every localization.
44+
XCUIElementQuery *alertButtons = permissionAlert.buttons;
45+
NSUInteger buttonCount = alertButtons.count;
46+
if (buttonCount == 0) {
47+
XCTFail(@"Sign In permission alert has no buttons");
48+
}
49+
[[alertButtons elementBoundByIndex:buttonCount - 1] tap];
4250
} else {
4351
os_log(OS_LOG_DEFAULT, "Permission alert not detected, continuing.");
4452
}

‎packages/google_sign_in/google_sign_in_ios/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: google_sign_in_ios
22
description: iOS implementation of the google_sign_in plugin.
33
repository: https://github.com/flutter/packages/tree/main/packages/google_sign_in/google_sign_in_ios
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22
5-
version: 6.3.0
5+
version: 6.3.1
66

77
environment:
88
sdk: ^3.10.0

0 commit comments

Comments
 (0)