diff --git a/Sources/UberAuth/Token/AccessToken.swift b/Sources/UberAuth/Token/AccessToken.swift index 57d0c488..0f742ce5 100644 --- a/Sources/UberAuth/Token/AccessToken.swift +++ b/Sources/UberAuth/Token/AccessToken.swift @@ -59,7 +59,7 @@ public struct AccessToken: Codable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let tokenString = try container.decode(String.self, forKey: .tokenString) - let tokenType = try container.decode(String.self, forKey: .tokenType) + let tokenType = try container.decodeIfPresent(String.self, forKey: .tokenType) let expiresIn = try container.decodeIfPresent(Int.self, forKey: .expiresIn) let refreshToken = try container.decodeIfPresent(String.self, forKey: .refreshToken) diff --git a/Sources/UberRides/RideRequestView.swift b/Sources/UberRides/RideRequestView.swift index 6923fad5..5f773f37 100644 --- a/Sources/UberRides/RideRequestView.swift +++ b/Sources/UberRides/RideRequestView.swift @@ -107,8 +107,10 @@ public class RideRequestView: UIView { - returns: An initialized RideRequestView */ - public convenience init(rideParameters: RideParameters) { - self.init(rideParameters: rideParameters, accessToken: Self.tokenManager.getToken(), frame: CGRect.zero) + public convenience init(rideParameters: RideParameters, + accessTokenIdentifier: String = TokenManager.defaultAccessTokenIdentifier, + accessGroup: String? = nil) { + self.init(rideParameters: rideParameters, accessToken: Self.tokenManager.getToken(identifier: accessTokenIdentifier, accessGroup: accessGroup), frame: CGRect.zero) } /** @@ -132,8 +134,12 @@ public class RideRequestView: UIView { - returns: An initialized RideRequestView */ - public convenience init() { - self.init(rideParameters: RideParametersBuilder().build(), accessToken: Self.tokenManager.getToken(), frame: CGRect.zero) + public convenience init(accessTokenIdentifier: String = TokenManager.defaultAccessTokenIdentifier) { + self.init( + rideParameters: RideParametersBuilder().build(), + accessToken: Self.tokenManager.getToken(identifier: accessTokenIdentifier), + frame: CGRect.zero + ) } required public init?(coder aDecoder: NSCoder) { diff --git a/Sources/UberRides/RideRequestViewController.swift b/Sources/UberRides/RideRequestViewController.swift index 835cac77..28e7ceca 100644 --- a/Sources/UberRides/RideRequestViewController.swift +++ b/Sources/UberRides/RideRequestViewController.swift @@ -54,7 +54,7 @@ public class RideRequestViewController: UIViewController { /// The RideRequestViewControllerDelegate to handle the errors public var delegate: RideRequestViewControllerDelegate? - lazy var rideRequestView: RideRequestView = RideRequestView() + lazy var rideRequestView: RideRequestView = RideRequestView(accessTokenIdentifier: accessTokenIdentifier) static let sourceString = "ride_request_widget" @@ -62,10 +62,8 @@ public class RideRequestViewController: UIViewController { private var loginCompletion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)? private let tokenManager = TokenManager() - - // TODO: Support custom accessTokenIdentifier, keychainAccessGroup - private let accessTokenIdentifier: String = "" - private let keychainAccessGroup: String = "" + private let accessTokenIdentifier: String + private let keychainAccessGroup: String /** Initializes a RideRequestViewController using the provided coder. By default, @@ -76,6 +74,9 @@ public class RideRequestViewController: UIViewController { - returns: An initialized RideRequestViewController, or nil if something went wrong */ public required init?(coder aDecoder: NSCoder) { + self.accessTokenIdentifier = Configuration.shared.defaultAccessTokenIdentifier + self.keychainAccessGroup = Configuration.shared.defaultKeychainAccessGroup + super.init(coder: aDecoder) let defaultRideParameters = RideParametersBuilder() @@ -92,7 +93,13 @@ public class RideRequestViewController: UIViewController { - returns: An initialized RideRequestViewController */ - public init(rideParameters: RideParameters) { + public init(rideParameters: RideParameters, + accessTokenIdentifier: String = Configuration.shared.defaultAccessTokenIdentifier, + keychainAccessGroup: String = Configuration.shared.defaultKeychainAccessGroup) { + + self.accessTokenIdentifier = accessTokenIdentifier + self.keychainAccessGroup = keychainAccessGroup + super.init(nibName: nil, bundle: nil) rideParameters.source = rideParameters.source ?? RideRequestViewController.sourceString diff --git a/Sources/UberRides/RideRequestViewRequestingBehavior.swift b/Sources/UberRides/RideRequestViewRequestingBehavior.swift index c61fdfca..bf398a54 100644 --- a/Sources/UberRides/RideRequestViewRequestingBehavior.swift +++ b/Sources/UberRides/RideRequestViewRequestingBehavior.swift @@ -50,9 +50,15 @@ public class RideRequestViewRequestingBehavior { - returns: An initialized RideRequestViewRequestingBehavior object */ - public init(presentingViewController: UIViewController) { + public init(presentingViewController: UIViewController, + accessTokenIdentifier: String = Configuration.shared.defaultAccessTokenIdentifier, + keychainAccessGroup: String = Configuration.shared.defaultKeychainAccessGroup) { self.presentingViewController = presentingViewController - let rideRequestViewController = RideRequestViewController(rideParameters: RideParametersBuilder().build()) + let rideRequestViewController = RideRequestViewController( + rideParameters: RideParametersBuilder().build(), + accessTokenIdentifier: accessTokenIdentifier, + keychainAccessGroup: keychainAccessGroup + ) modalRideRequestViewController = ModalRideRequestViewController(rideRequestViewController: rideRequestViewController) } } diff --git a/examples/Swift SDK/Swift SDK.xcodeproj/project.pbxproj b/examples/Swift SDK/Swift SDK.xcodeproj/project.pbxproj index 908f100e..406dac9a 100644 --- a/examples/Swift SDK/Swift SDK.xcodeproj/project.pbxproj +++ b/examples/Swift SDK/Swift SDK.xcodeproj/project.pbxproj @@ -59,22 +59,7 @@ B206F26C2B7ACAFA0006C554 /* DeeplinkRequestingBehaviorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F22C2B7ACAFA0006C554 /* DeeplinkRequestingBehaviorTests.swift */; }; B206F26D2B7ACAFA0006C554 /* RequestButtonTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F22D2B7ACAFA0006C554 /* RequestButtonTests.swift */; }; B206F26F2B7ACAFA0006C554 /* RidesMocks.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F22F2B7ACAFA0006C554 /* RidesMocks.swift */; }; - B206F2702B7ACAFA0006C554 /* LoginManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2322B7ACAFA0006C554 /* LoginManagerTests.swift */; }; - B206F2712B7ACAFA0006C554 /* AsyncDispatcherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2332B7ACAFA0006C554 /* AsyncDispatcherTests.swift */; }; - B206F2722B7ACAFA0006C554 /* TokenManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2342B7ACAFA0006C554 /* TokenManagerTests.swift */; }; - B206F2732B7ACAFA0006C554 /* RidesAuthenticationDeeplinkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2352B7ACAFA0006C554 /* RidesAuthenticationDeeplinkTests.swift */; }; - B206F2742B7ACAFA0006C554 /* AuthenticationURLUtilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2362B7ACAFA0006C554 /* AuthenticationURLUtilityTests.swift */; }; - B206F2752B7ACAFA0006C554 /* LoginButtonTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2372B7ACAFA0006C554 /* LoginButtonTests.swift */; }; - B206F2762B7ACAFA0006C554 /* RefreshEndpointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2382B7ACAFA0006C554 /* RefreshEndpointTests.swift */; }; - B206F2772B7ACAFA0006C554 /* OauthEndpointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2392B7ACAFA0006C554 /* OauthEndpointTests.swift */; }; - B206F2782B7ACAFA0006C554 /* UberAppDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F23A2B7ACAFA0006C554 /* UberAppDelegateTests.swift */; }; - B206F2792B7ACAFA0006C554 /* ConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F23B2B7ACAFA0006C554 /* ConfigurationTests.swift */; }; - B206F27A2B7ACAFA0006C554 /* OAuthTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F23C2B7ACAFA0006C554 /* OAuthTests.swift */; }; - B206F27B2B7ACAFA0006C554 /* UberMocks.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F23D2B7ACAFA0006C554 /* UberMocks.swift */; }; B206F27C2B7ACAFA0006C554 /* DeeplinkManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F23E2B7ACAFA0006C554 /* DeeplinkManagerTests.swift */; }; - B206F27D2B7ACAFA0006C554 /* BaseAuthenticatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F23F2B7ACAFA0006C554 /* BaseAuthenticatorTests.swift */; }; - B206F27E2B7ACAFA0006C554 /* DeeplinkErrorFactoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2402B7ACAFA0006C554 /* DeeplinkErrorFactoryTests.swift */; }; - B206F2802B7ACAFA0006C554 /* AccessTokenFactoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2422B7ACAFA0006C554 /* AccessTokenFactoryTests.swift */; }; B206F2812B7ACAFA0006C554 /* BaseDeeplinkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B206F2432B7ACAFA0006C554 /* BaseDeeplinkTests.swift */; }; B206F2842B7ACB290006C554 /* OHHTTPStubs in Frameworks */ = {isa = PBXBuildFile; productRef = B206F2832B7ACB290006C554 /* OHHTTPStubs */; }; B206F2862B7ACB290006C554 /* OHHTTPStubsSwift in Frameworks */ = {isa = PBXBuildFile; productRef = B206F2852B7ACB290006C554 /* OHHTTPStubsSwift */; }; @@ -174,32 +159,11 @@ B206F22C2B7ACAFA0006C554 /* DeeplinkRequestingBehaviorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeeplinkRequestingBehaviorTests.swift; sourceTree = ""; }; B206F22D2B7ACAFA0006C554 /* RequestButtonTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestButtonTests.swift; sourceTree = ""; }; B206F22F2B7ACAFA0006C554 /* RidesMocks.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RidesMocks.swift; sourceTree = ""; }; - B206F2322B7ACAFA0006C554 /* LoginManagerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoginManagerTests.swift; sourceTree = ""; }; - B206F2332B7ACAFA0006C554 /* AsyncDispatcherTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AsyncDispatcherTests.swift; sourceTree = ""; }; - B206F2342B7ACAFA0006C554 /* TokenManagerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TokenManagerTests.swift; sourceTree = ""; }; - B206F2352B7ACAFA0006C554 /* RidesAuthenticationDeeplinkTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RidesAuthenticationDeeplinkTests.swift; sourceTree = ""; }; - B206F2362B7ACAFA0006C554 /* AuthenticationURLUtilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthenticationURLUtilityTests.swift; sourceTree = ""; }; - B206F2372B7ACAFA0006C554 /* LoginButtonTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoginButtonTests.swift; sourceTree = ""; }; - B206F2382B7ACAFA0006C554 /* RefreshEndpointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RefreshEndpointTests.swift; sourceTree = ""; }; - B206F2392B7ACAFA0006C554 /* OauthEndpointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OauthEndpointTests.swift; sourceTree = ""; }; - B206F23A2B7ACAFA0006C554 /* UberAppDelegateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UberAppDelegateTests.swift; sourceTree = ""; }; - B206F23B2B7ACAFA0006C554 /* ConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConfigurationTests.swift; sourceTree = ""; }; - B206F23C2B7ACAFA0006C554 /* OAuthTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuthTests.swift; sourceTree = ""; }; - B206F23D2B7ACAFA0006C554 /* UberMocks.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UberMocks.swift; sourceTree = ""; }; B206F23E2B7ACAFA0006C554 /* DeeplinkManagerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeeplinkManagerTests.swift; sourceTree = ""; }; - B206F23F2B7ACAFA0006C554 /* BaseAuthenticatorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseAuthenticatorTests.swift; sourceTree = ""; }; - B206F2402B7ACAFA0006C554 /* DeeplinkErrorFactoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeeplinkErrorFactoryTests.swift; sourceTree = ""; }; - B206F2422B7ACAFA0006C554 /* AccessTokenFactoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AccessTokenFactoryTests.swift; sourceTree = ""; }; B206F2432B7ACAFA0006C554 /* BaseDeeplinkTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseDeeplinkTests.swift; sourceTree = ""; }; B206F2882B7ACBBC0006C554 /* testInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = testInfo.plist; sourceTree = ""; }; B206F2892B7ACBBC0006C554 /* testInfoMissingCallbacks.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = testInfoMissingCallbacks.plist; sourceTree = ""; }; - B29302FD2B890D5800D28BAA /* UberSampleApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UberSampleApp.swift; sourceTree = ""; }; - B29302FF2B890D5800D28BAA /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; - B29303012B890D5800D28BAA /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - B29303042B890D5800D28BAA /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; - B293030E2B890D5900D28BAA /* UberSampleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UberSampleTests.swift; sourceTree = ""; }; - B29303182B890D5900D28BAA /* UberSampleUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UberSampleUITests.swift; sourceTree = ""; }; - B293031A2B890D5900D28BAA /* UberSampleUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UberSampleUITestsLaunchTests.swift; sourceTree = ""; }; + B2156C1B2C2B58D700C6BDDD /* Swift SDK.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "Swift SDK.entitlements"; sourceTree = ""; }; D825C5C91CD19773001FE3A7 /* AuthorizationCodeGrantExampleViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthorizationCodeGrantExampleViewController.swift; sourceTree = ""; }; D825C5CB1CD267C0001FE3A7 /* AuthorizationBaseViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthorizationBaseViewController.swift; sourceTree = ""; }; DC78EC771CB34AC600850814 /* ExampleTableViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExampleTableViewController.swift; sourceTree = ""; }; @@ -250,9 +214,6 @@ AC0404A61BFAD0C800AC1501 /* Swift SDK */, AC0404BB1BFAD0C800AC1501 /* Swift SDKTests */, AC0404C61BFAD0C800AC1501 /* Swift SDKUITests */, - B29302FC2B890D5800D28BAA /* UberSample */, - B293030D2B890D5900D28BAA /* UberSampleTests */, - B29303172B890D5900D28BAA /* UberSampleUITests */, AC0404A51BFAD0C800AC1501 /* Products */, ); sourceTree = ""; @@ -270,6 +231,7 @@ AC0404A61BFAD0C800AC1501 /* Swift SDK */ = { isa = PBXGroup; children = ( + B2156C1B2C2B58D700C6BDDD /* Swift SDK.entitlements */, B206F2872B7ACB5A0006C554 /* TestData */, AC0404A71BFAD0C800AC1501 /* AppDelegate.swift */, DC78EC771CB34AC600850814 /* ExampleTableViewController.swift */, @@ -290,7 +252,6 @@ AC0404BB1BFAD0C800AC1501 /* Swift SDKTests */ = { isa = PBXGroup; children = ( - B206F2302B7ACAFA0006C554 /* UberAuth */, B206F2312B7ACAFA0006C554 /* UberCore */, B206F2022B7ACAFA0006C554 /* UberRides */, AC0404BE1BFAD0C800AC1501 /* Info.plist */, @@ -365,32 +326,10 @@ path = TestData; sourceTree = ""; }; - B206F2302B7ACAFA0006C554 /* UberAuth */ = { - isa = PBXGroup; - children = ( - ); - path = UberAuth; - sourceTree = ""; - }; B206F2312B7ACAFA0006C554 /* UberCore */ = { isa = PBXGroup; children = ( - B206F2322B7ACAFA0006C554 /* LoginManagerTests.swift */, - B206F2332B7ACAFA0006C554 /* AsyncDispatcherTests.swift */, - B206F2342B7ACAFA0006C554 /* TokenManagerTests.swift */, - B206F2352B7ACAFA0006C554 /* RidesAuthenticationDeeplinkTests.swift */, - B206F2362B7ACAFA0006C554 /* AuthenticationURLUtilityTests.swift */, - B206F2372B7ACAFA0006C554 /* LoginButtonTests.swift */, - B206F2382B7ACAFA0006C554 /* RefreshEndpointTests.swift */, - B206F2392B7ACAFA0006C554 /* OauthEndpointTests.swift */, - B206F23A2B7ACAFA0006C554 /* UberAppDelegateTests.swift */, - B206F23B2B7ACAFA0006C554 /* ConfigurationTests.swift */, - B206F23C2B7ACAFA0006C554 /* OAuthTests.swift */, - B206F23D2B7ACAFA0006C554 /* UberMocks.swift */, B206F23E2B7ACAFA0006C554 /* DeeplinkManagerTests.swift */, - B206F23F2B7ACAFA0006C554 /* BaseAuthenticatorTests.swift */, - B206F2402B7ACAFA0006C554 /* DeeplinkErrorFactoryTests.swift */, - B206F2422B7ACAFA0006C554 /* AccessTokenFactoryTests.swift */, B206F2432B7ACAFA0006C554 /* BaseDeeplinkTests.swift */, ); path = UberCore; @@ -405,42 +344,6 @@ path = TestData; sourceTree = ""; }; - B29302FC2B890D5800D28BAA /* UberSample */ = { - isa = PBXGroup; - children = ( - B29302FD2B890D5800D28BAA /* UberSampleApp.swift */, - B29302FF2B890D5800D28BAA /* ContentView.swift */, - B29303012B890D5800D28BAA /* Assets.xcassets */, - B29303032B890D5800D28BAA /* Preview Content */, - ); - path = UberSample; - sourceTree = ""; - }; - B29303032B890D5800D28BAA /* Preview Content */ = { - isa = PBXGroup; - children = ( - B29303042B890D5800D28BAA /* Preview Assets.xcassets */, - ); - path = "Preview Content"; - sourceTree = ""; - }; - B293030D2B890D5900D28BAA /* UberSampleTests */ = { - isa = PBXGroup; - children = ( - B293030E2B890D5900D28BAA /* UberSampleTests.swift */, - ); - path = UberSampleTests; - sourceTree = ""; - }; - B29303172B890D5900D28BAA /* UberSampleUITests */ = { - isa = PBXGroup; - children = ( - B29303182B890D5900D28BAA /* UberSampleUITests.swift */, - B293031A2B890D5900D28BAA /* UberSampleUITestsLaunchTests.swift */, - ); - path = UberSampleUITests; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -637,40 +540,25 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - B206F2742B7ACAFA0006C554 /* AuthenticationURLUtilityTests.swift in Sources */, B206F2612B7ACAFA0006C554 /* RideRequestViewControllerTests.swift in Sources */, B206F2672B7ACAFA0006C554 /* URLComponentsExtensionsTests.swift in Sources */, B206F2682B7ACAFA0006C554 /* RequestDeeplinkTests.swift in Sources */, B206F26C2B7ACAFA0006C554 /* DeeplinkRequestingBehaviorTests.swift in Sources */, B206F2632B7ACAFA0006C554 /* RidesAuthenticationErrorFactoryTests.swift in Sources */, - B206F2702B7ACAFA0006C554 /* LoginManagerTests.swift in Sources */, B206F2662B7ACAFA0006C554 /* WidgetsEndpointTests.swift in Sources */, - B206F27D2B7ACAFA0006C554 /* BaseAuthenticatorTests.swift in Sources */, B206F2652B7ACAFA0006C554 /* RidesScopeExtensionsTests.swift in Sources */, - B206F2752B7ACAFA0006C554 /* LoginButtonTests.swift in Sources */, B206F25F2B7ACAFA0006C554 /* ModalViewControllerTests.swift in Sources */, - B206F2732B7ACAFA0006C554 /* RidesAuthenticationDeeplinkTests.swift in Sources */, B206F2692B7ACAFA0006C554 /* RideRequestViewRequestingBehaviorTests.swift in Sources */, - B206F2772B7ACAFA0006C554 /* OauthEndpointTests.swift in Sources */, - B206F2782B7ACAFA0006C554 /* UberAppDelegateTests.swift in Sources */, B206F27C2B7ACAFA0006C554 /* DeeplinkManagerTests.swift in Sources */, B206F25E2B7ACAFA0006C554 /* ObjectMappingTests.swift in Sources */, - B206F2712B7ACAFA0006C554 /* AsyncDispatcherTests.swift in Sources */, - B206F27A2B7ACAFA0006C554 /* OAuthTests.swift in Sources */, B206F2812B7ACAFA0006C554 /* BaseDeeplinkTests.swift in Sources */, B206F26A2B7ACAFA0006C554 /* RidesClientTests.swift in Sources */, B206F2642B7ACAFA0006C554 /* RideRequestViewTests.swift in Sources */, - B206F27B2B7ACAFA0006C554 /* UberMocks.swift in Sources */, B206F2442B7ACAFA0006C554 /* RideParametersTest.swift in Sources */, - B206F2802B7ACAFA0006C554 /* AccessTokenFactoryTests.swift in Sources */, - B206F2762B7ACAFA0006C554 /* RefreshEndpointTests.swift in Sources */, - B206F2722B7ACAFA0006C554 /* TokenManagerTests.swift in Sources */, B206F26D2B7ACAFA0006C554 /* RequestButtonTests.swift in Sources */, - B206F27E2B7ACAFA0006C554 /* DeeplinkErrorFactoryTests.swift in Sources */, B206F2602B7ACAFA0006C554 /* RequestURLUtilTests.swift in Sources */, B206F2452B7ACAFA0006C554 /* RequestLayerTests.swift in Sources */, B206F26B2B7ACAFA0006C554 /* RideRequestViewErrorFactoryTests.swift in Sources */, - B206F2792B7ACAFA0006C554 /* ConfigurationTests.swift in Sources */, B206F2622B7ACAFA0006C554 /* APIManagerTests.swift in Sources */, B206F26F2B7ACAFA0006C554 /* RidesMocks.swift in Sources */, ); @@ -834,12 +722,13 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = "Swift SDK/Swift SDK.entitlements"; CODE_SIGN_IDENTITY = "iPhone Developer"; DEVELOPMENT_TEAM = 5F83KRY2FH; FRAMEWORK_SEARCH_PATHS = "$(inherited)"; HEADER_SEARCH_PATHS = ""; INFOPLIST_FILE = "Swift SDK/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -855,12 +744,13 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = "Swift SDK/Swift SDK.entitlements"; CODE_SIGN_IDENTITY = "iPhone Developer"; DEVELOPMENT_TEAM = 5F83KRY2FH; FRAMEWORK_SEARCH_PATHS = "$(inherited)"; HEADER_SEARCH_PATHS = ""; INFOPLIST_FILE = "Swift SDK/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -877,7 +767,7 @@ buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = "Swift SDKTests/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -896,7 +786,7 @@ buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = "Swift SDKTests/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -914,7 +804,7 @@ isa = XCBuildConfiguration; buildSettings = { INFOPLIST_FILE = "Swift SDKUITests/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -933,7 +823,7 @@ isa = XCBuildConfiguration; buildSettings = { INFOPLIST_FILE = "Swift SDKUITests/Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", diff --git a/examples/Swift SDK/Swift SDK/AppDelegate.swift b/examples/Swift SDK/Swift SDK/AppDelegate.swift index 3d23b1db..a0a4fea4 100644 --- a/examples/Swift SDK/Swift SDK/AppDelegate.swift +++ b/examples/Swift SDK/Swift SDK/AppDelegate.swift @@ -23,6 +23,7 @@ // THE SOFTWARE. import UIKit +import UberAuth import UberCore import UberRides @@ -32,16 +33,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - - // Uncomment if your app is registered in China - //Configuration.setRegion(.China) - - // Make requests to sandbox by default - Configuration.shared.isSandbox = true - - // Handle incoming SSO Requests - _ = UberAppDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) return true } @@ -69,15 +60,17 @@ class AppDelegate: UIResponder, UIApplicationDelegate { @available(iOS 9, *) func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { - let handledUberURL = UberAppDelegate.shared.application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation] as Any) - - return handledUberURL + if UberAuth.handle(url) { + return false + } + return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { - let handledUberURL = UberAppDelegate.shared.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) - - return handledUberURL + if UberAuth.handle(url) { + return false + } + return true } } diff --git a/examples/Swift SDK/Swift SDK/AuthorizationBaseViewController.swift b/examples/Swift SDK/Swift SDK/AuthorizationBaseViewController.swift index c986e716..30f2f000 100644 --- a/examples/Swift SDK/Swift SDK/AuthorizationBaseViewController.swift +++ b/examples/Swift SDK/Swift SDK/AuthorizationBaseViewController.swift @@ -22,12 +22,15 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +import UberAuth import UberCore import UberRides import UIKit class AuthorizationBaseViewController: UIViewController { + private let tokenManager = TokenManager() + func delay(_ delay: Int, closure: @escaping ()->()) { let deadlineTime = DispatchTime.now() + DispatchTimeInterval.seconds(delay) DispatchQueue.main.asyncAfter(deadline: deadlineTime) { @@ -45,7 +48,7 @@ class AuthorizationBaseViewController: UIViewController { func checkError(_ response: Response) { // Unauthorized if response.statusCode == 401 { - _ = TokenManager.deleteToken() + _ = tokenManager.deleteToken() DispatchQueue.main.async { self.reset() } diff --git a/examples/Swift SDK/Swift SDK/AuthorizationCodeGrantExampleViewController.swift b/examples/Swift SDK/Swift SDK/AuthorizationCodeGrantExampleViewController.swift index 3b95b489..9fdea251 100644 --- a/examples/Swift SDK/Swift SDK/AuthorizationCodeGrantExampleViewController.swift +++ b/examples/Swift SDK/Swift SDK/AuthorizationCodeGrantExampleViewController.swift @@ -23,6 +23,7 @@ // THE SOFTWARE. import CoreLocation +import UberAuth import UberCore import UberRides import UIKit @@ -34,13 +35,11 @@ class AuthorizationCodeGrantExampleViewController: AuthorizationBaseViewControll fileprivate let states = ["accepted", "arriving", "in_progress", "completed"] - /// The LoginManager to use for login - /// Specify authorization code grant as the loginType to use privileged scopes - let loginManager = LoginManager(loginType: .authorizationCode) - /// The RidesClient to use for endpoints let ridesClient = RidesClient() + private let tokenManager = TokenManager() + @IBOutlet weak var driverImageView: UIImageView! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var loginButton: UIBarButtonItem! @@ -58,7 +57,7 @@ class AuthorizationCodeGrantExampleViewController: AuthorizationBaseViewControll override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) - let loggedIn = TokenManager.fetchToken() != nil + let loggedIn = tokenManager.getToken() != nil loginButton.isEnabled = !loggedIn requestButton.isEnabled = loggedIn @@ -78,38 +77,33 @@ class AuthorizationCodeGrantExampleViewController: AuthorizationBaseViewControll // Need to be authorized on your developer dashboard at developer.uber.com // Privileged scopes can be used by anyone in sandbox for your own account but must be approved for production let requestedScopes = [UberScope.request, UberScope.allTrips] - // Use your loginManager to login with the requested scopes, viewcontroller to present over, and completion block - loginManager.login(requestedScopes: requestedScopes, presentingViewController: self) { (accessToken, error) -> () in - // Error - if let error = error { - self.showMessage(error.localizedDescription) - return - } - - // Poll backend for access token - // Replace "YOUR_URL" with the path for your backend service - if let url = URL(string: "YOUR_URL") { - let request = URLRequest(url: url) - URLSession.shared.dataTask(with: request) { (data, response, error) in - DispatchQueue.main.async { - guard let data = data, - let jsonString = String(data: data, encoding: String.Encoding.utf8) else { - self.showMessage("Unable to retrieve access token") - return - } - let token = AccessToken(tokenString: jsonString) - - // Do any additional work to verify the state passed in earlier - - if !TokenManager.save(accessToken: token) { - self.showMessage("Unable to save access token") - } else { - self.showMessage("Saved an AccessToken!") - self.loginButton.isEnabled = false - self.requestButton.isEnabled = true - } + let scopes = requestedScopes.map { $0.rawValue } + + let context = AuthContext( + authDestination: .inApp, + authProvider: .authorizationCode(scopes: scopes, shouldExchangeAuthCode: true) + ) + + UberAuth.login(context: context) { result in + DispatchQueue.main.async { + switch result { + case .success(let client): + guard let accessToken = client.accessToken else { + self.showMessage("Unable to retrieve access token") + return } - }.resume() + + if !self.tokenManager.saveToken(accessToken) { + self.showMessage("Unable to save access token") + } else { + self.showMessage("Saved an AccessToken!") + self.loginButton.isEnabled = false + self.requestButton.isEnabled = true + } + + case .failure(let error): + self.showMessage(error.localizedDescription) + } } } } @@ -194,7 +188,7 @@ class AuthorizationCodeGrantExampleViewController: AuthorizationBaseViewControll // Simulates stepping through ride statuses recursively func updateRideStatus(_ requestID: String, index: Int) { guard index < states.count, - let token = TokenManager.fetchToken() else { + let token = tokenManager.getToken()?.tokenString else { return } @@ -204,7 +198,7 @@ class AuthorizationCodeGrantExampleViewController: AuthorizationBaseViewControll let updateStatusEndpoint = URL(string: "https://sandbox-api.uber.com/v1/sandbox/requests/\(requestID)")! var request = URLRequest(url: updateStatusEndpoint) request.httpMethod = "PUT" - request.setValue("Bearer \(token.tokenString)", forHTTPHeaderField: "Authorization") + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "Content-Type") do { let data = try JSONSerialization.data(withJSONObject: ["status":status], options: .prettyPrinted) diff --git a/examples/Swift SDK/Swift SDK/ExampleTableViewController.swift b/examples/Swift SDK/Swift SDK/ExampleTableViewController.swift index 896f822f..3041bb11 100644 --- a/examples/Swift SDK/Swift SDK/ExampleTableViewController.swift +++ b/examples/Swift SDK/Swift SDK/ExampleTableViewController.swift @@ -23,6 +23,7 @@ // THE SOFTWARE. import UIKit +import UberAuth import UberCore import UberRides @@ -30,6 +31,8 @@ class ExampleTableViewController: UITableViewController { let authorizationCodeGrantSegueIdentifier = "AuthorizationCodeGrantSegue" let implicitGrantSegueIdentifier = "ImplicitGrantSegue" + + private let tokenManager = TokenManager() override func viewDidLoad() { super.viewDidLoad() @@ -101,7 +104,7 @@ class ExampleTableViewController: UITableViewController { } case 1: viewControllerToPush = nil - _ = TokenManager.deleteToken() + _ = tokenManager.deleteToken() default: viewControllerToPush = nil } diff --git a/examples/Swift SDK/Swift SDK/ImplicitGrantExampleViewController.swift b/examples/Swift SDK/Swift SDK/ImplicitGrantExampleViewController.swift index e4ffca92..3cd282f4 100644 --- a/examples/Swift SDK/Swift SDK/ImplicitGrantExampleViewController.swift +++ b/examples/Swift SDK/Swift SDK/ImplicitGrantExampleViewController.swift @@ -23,6 +23,7 @@ // THE SOFTWARE. import UIKit +import UberAuth import UberRides import UberCore import CoreLocation @@ -30,8 +31,8 @@ import CoreLocation /// This class demonstrates how do use the LoginManager to complete Implicit Grant Authorization /// and how to use the user profile, trip history, and places endpoints. class ImplicitGrantExampleViewController: AuthorizationBaseViewController { - /// The LoginManager to use for login - let loginManager = LoginManager(loginType: .implicit) + + private let tokenManager = TokenManager() /// The RidesClient to use for endpoints let ridesClient = RidesClient() @@ -70,7 +71,7 @@ class ImplicitGrantExampleViewController: AuthorizationBaseViewController { } override func viewWillAppear(_ animated: Bool) { - if let _ = TokenManager.fetchToken() { + if let _ = tokenManager.getToken() { loginButton.isEnabled = false getData() } @@ -87,17 +88,17 @@ class ImplicitGrantExampleViewController: AuthorizationBaseViewController { // Need to be authorized on your developer dashboard at developer.uber.com let requestedScopes = [UberScope.rideWidgets, UberScope.profile, UberScope.places, UberScope.history, UberScope.places] // Use your loginManager to login with the requested scopes, viewcontroller to present over, and completion block - loginManager.login(requestedScopes: requestedScopes, presentingViewController: self) { (accessToken, error) -> () in - if accessToken != nil { - //Success! AccessToken is automatically saved in keychain + + let context = AuthContext( + authProvider: .authorizationCode(scopes: requestedScopes.map { $0.rawValue }) + ) + + UberAuth.login(context: context) { result in + switch result { + case .success: self.showMessage("Got an AccessToken!") - } else { - // Error - if let error = error { - self.showMessage(error.localizedDescription) - } else { - self.showMessage("An Unknown Error Occured") - } + case .failure(let error): + self.showMessage(error.localizedDescription) } } } diff --git a/examples/Swift SDK/Swift SDK/Info.plist b/examples/Swift SDK/Swift SDK/Info.plist index 204b47b7..eb93fd39 100644 --- a/examples/Swift SDK/Swift SDK/Info.plist +++ b/examples/Swift SDK/Swift SDK/Info.plist @@ -33,6 +33,8 @@ 1 LSApplicationQueriesSchemes + uberdriver + ubereats uberauth uber @@ -54,18 +56,16 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight - UberCallbackURIs - - - URIString - com.uber.sdk.Swift-SDK://oauth/consumer - UberCallbackURIType - General - - UberClientID - fNuupfZ-F6YinKzoGLSo_ktxipTx0M-5 + 9QZcD_Ki6NbhGCrVXSUHCxfevm-C9Khj UberDisplayName Rides SDK Demo App + UberAuth + + ClientID + 9QZcD_Ki6NbhGCrVXSUHCxfevm-C9Khj + RedirectURI + com.uber.sdk.Swift-SDK://oauth/consumer + diff --git a/examples/Swift SDK/Swift SDK/NativeLoginExampleViewController.swift b/examples/Swift SDK/Swift SDK/NativeLoginExampleViewController.swift index ccfdde4f..3a5aba4c 100644 --- a/examples/Swift SDK/Swift SDK/NativeLoginExampleViewController.swift +++ b/examples/Swift SDK/Swift SDK/NativeLoginExampleViewController.swift @@ -23,6 +23,7 @@ // THE SOFTWARE. import UIKit +import UberAuth import UberCore import UberRides import CoreLocation @@ -31,23 +32,17 @@ import CoreLocation open class NativeLoginExampleViewController: ButtonExampleViewController, LoginButtonDelegate { let scopes: [UberScope] - let loginManager: LoginManager let blackLoginButton: LoginButton let whiteLoginButton: LoginButton override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { scopes = [.profile, .places, .request] - - loginManager = LoginManager(loginType: .native) - blackLoginButton = LoginButton(frame: CGRect.zero, scopes: scopes, loginManager: loginManager) - whiteLoginButton = LoginButton(frame: CGRect.zero, scopes: scopes, loginManager: loginManager) - - whiteLoginButton.colorStyle = .white + + // TODO: Light/Dark override + blackLoginButton = LoginButton() + whiteLoginButton = LoginButton() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) - - blackLoginButton.presentingViewController = self - whiteLoginButton.presentingViewController = self blackLoginButton.delegate = self whiteLoginButton.delegate = self @@ -106,13 +101,12 @@ open class NativeLoginExampleViewController: ButtonExampleViewController, LoginB } } - open func loginButton(_ button: LoginButton, didCompleteLoginWithToken accessToken: AccessToken?, error: NSError?) { - if let _ = accessToken { + open func loginButton(_ button: LoginButton, didCompleteLoginWithResult result: Result) { + switch result { + case .success: showMessage("Saved access token!") - } else if let error = error { + case .failure(let error): showMessage(error.localizedDescription) - } else { - showMessage("Error") } } } diff --git a/examples/Swift SDK/Swift SDK.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/examples/Swift SDK/Swift SDK/Swift SDK.entitlements similarity index 61% rename from examples/Swift SDK/Swift SDK.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename to examples/Swift SDK/Swift SDK/Swift SDK.entitlements index 18d98100..955d983d 100644 --- a/examples/Swift SDK/Swift SDK.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ b/examples/Swift SDK/Swift SDK/Swift SDK.entitlements @@ -2,7 +2,9 @@ - IDEDidComputeMac32BitWarning - + keychain-access-groups + + $(AppIdentifierPrefix)com.uber.sdk.Swift-SDK + diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/AccessTokenFactoryTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/AccessTokenFactoryTests.swift deleted file mode 100644 index db9eddf9..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/AccessTokenFactoryTests.swift +++ /dev/null @@ -1,234 +0,0 @@ -// -// AccessTokenFactorytests.swift -// UberRides -// -// Copyright © 2015 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -@testable import UberCore - -class AccessTokenFactoryTests: XCTestCase { - private let scheme = "http" - private let redirectURI = "localhost" - private let port = 1234 - private let tokenString = "token" - private let tokenTypeString = "type" - private let refreshTokenString = "refreshToken" - private let expirationTime = 10030.23 - private let allowedScopesString = "profile history" - private let errorString = "invalid_parameters" - - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - - func testParseTokenFromURL_withSuccess() { - var components = URLComponents() - components.fragment = "access_token=\(tokenString)&refresh_token=\(refreshTokenString)&token_type=\(tokenTypeString)&expires_in=\(expirationTime)&scope=\(allowedScopesString)" - components.host = redirectURI - components.scheme = scheme - components.port = port - - guard let url = components.url else { - XCTAssert(false) - return - } - do { - let token : AccessToken = try AccessTokenFactory.createAccessToken(fromRedirectURL: url) - XCTAssertNotNil(token) - XCTAssertEqual(token.tokenString, tokenString) - XCTAssertEqual(token.refreshToken, refreshTokenString) - XCTAssertEqual(token.tokenType, tokenTypeString) - XCTAssertEqual(token.grantedScopes.toUberScopeString(), allowedScopesString) - UBSDKAssert(date: token.expirationDate!, approximatelyIn: expirationTime) - - } catch _ as NSError { - XCTAssert(false) - } catch { - XCTAssert(false) - } - } - - func testParseTokenFromURL_withError() { - var components = URLComponents() - components.fragment = "access_token=\(tokenString)&refresh_token=\(refreshTokenString)&token_type=\(tokenTypeString)&expires_in=\(expirationTime)&scope=\(allowedScopesString)&error=\(errorString)" - components.host = redirectURI - components.scheme = scheme - components.port = port - guard let url = components.url else { - XCTAssert(false) - return - } - do { - _ = try AccessTokenFactory.createAccessToken(fromRedirectURL: url) - XCTFail("Didn't parse out error") - } catch let error as NSError { - XCTAssertEqual(error.code, UberAuthenticationErrorType.invalidRequest.rawValue) - XCTAssertEqual(error.domain, UberAuthenticationErrorFactory.errorDomain) - } catch { - XCTAssert(false) - } - } - - func testParseTokenFromURL_withOnlyError() { - var components = URLComponents() - components.fragment = "error=\(errorString)" - components.host = redirectURI - components.scheme = scheme - components.port = port - guard let url = components.url else { - XCTAssert(false) - return - } - do { - _ = try AccessTokenFactory.createAccessToken(fromRedirectURL: url) - XCTFail("Didn't parse out error") - } catch let error as NSError { - XCTAssertEqual(error.code, UberAuthenticationErrorType.invalidRequest.rawValue) - XCTAssertEqual(error.domain, UberAuthenticationErrorFactory.errorDomain) - } catch { - XCTAssert(false) - } - } - - func testParseTokenFromURL_withPartialParameters() { - var components = URLComponents() - components.fragment = "access_token=\(tokenString)" - components.host = redirectURI - components.scheme = scheme - components.port = port - guard let url = components.url else { - XCTAssert(false) - return - } - do { - let token : AccessToken = try AccessTokenFactory.createAccessToken(fromRedirectURL: url) - XCTAssertNotNil(token) - XCTAssertEqual(token.tokenString, tokenString) - XCTAssertNil(token.refreshToken) - XCTAssertNil(token.tokenType) - XCTAssertNil(token.expirationDate) - XCTAssertEqual(token.grantedScopes, [UberScope]()) - } catch _ as NSError { - XCTAssert(false) - } catch { - XCTAssert(false) - } - } - - func testParseTokenFromURL_withFragmentAndQuery_withError() { - var components = URLComponents() - components.fragment = "access_token=\(tokenString)" - components.query = "error=\(errorString)" - components.host = redirectURI - components.scheme = scheme - components.port = port - guard let url = components.url else { - XCTAssert(false) - return - } - do { - _ = try AccessTokenFactory.createAccessToken(fromRedirectURL: url) - XCTFail("Didn't parse out error") - } catch let error as NSError { - XCTAssertEqual(error.code, UberAuthenticationErrorType.invalidRequest.rawValue) - XCTAssertEqual(error.domain, UberAuthenticationErrorFactory.errorDomain) - } catch { - XCTAssert(false) - } - } - - func testParseTokenFromURL_withFragmentAndQuery_withSuccess() { - var components = URLComponents(string: redirectURI)! - components.fragment = "access_token=\(tokenString)&refresh_token=\(refreshTokenString)&token_type=\(tokenTypeString)" - components.query = "expires_in=\(expirationTime)&scope=\(allowedScopesString)" - guard let url = components.url else { - XCTAssert(false) - return - } - do { - let token : AccessToken = try AccessTokenFactory.createAccessToken(fromRedirectURL: url) - XCTAssertNotNil(token) - XCTAssertEqual(token.tokenString, tokenString) - XCTAssertEqual(token.tokenType, tokenTypeString) - XCTAssertEqual(token.refreshToken, refreshTokenString) - XCTAssertEqual(token.grantedScopes.toUberScopeString(), allowedScopesString) - UBSDKAssert(date: token.expirationDate!, approximatelyIn: expirationTime) - - } catch { - XCTAssert(false) - } - } - - func testParseTokenFromURL_withInvalidFragment() { - var components = URLComponents() - components.fragment = "access_token=\(tokenString)&refresh_token" - components.host = redirectURI - components.scheme = scheme - components.port = port - guard let url = components.url else { - XCTAssert(false) - return - } - do { - let token : AccessToken = try AccessTokenFactory.createAccessToken(fromRedirectURL: url) - XCTAssertNotNil(token) - XCTAssertEqual(token.tokenString, tokenString) - XCTAssertNil(token.tokenType) - XCTAssertNil(token.refreshToken) - XCTAssertNil(token.expirationDate) - XCTAssertEqual(token.grantedScopes, [UberScope]()) - } catch _ as NSError { - XCTAssert(false) - } catch { - XCTAssert(false) - } - } - - func testParseValidJsonStringToAccessToken() { - let jsonString = "{\"access_token\": \"\(tokenString)\", \"refresh_token\": \"\(refreshTokenString)\", \"token_type\": \"\(tokenTypeString)\", \"expires_in\": \"\(expirationTime)\", \"scope\": \"\(allowedScopesString)\"}" - - guard let accessToken = try? AccessTokenFactory.createAccessToken(fromJSONData: jsonString.data(using: .utf8)!) else { - XCTFail() - return - } - XCTAssertEqual(accessToken.tokenString, tokenString) - XCTAssertEqual(accessToken.refreshToken, refreshTokenString) - XCTAssertEqual(accessToken.tokenType, tokenTypeString) - UBSDKAssert(date: accessToken.expirationDate!, approximatelyIn: expirationTime) - XCTAssert(accessToken.grantedScopes.contains(UberScope.profile)) - XCTAssert(accessToken.grantedScopes.contains(UberScope.history)) - } - - func testParseInvalidJsonStringToAccessToken() { - let tokenString = "tokenString1234" - let jsonString = "{\"access_token\": \"\(tokenString)\"" - let accessToken = try? AccessTokenFactory.createAccessToken(fromJSONData: jsonString.data(using: .utf8)!) - - XCTAssertNil(accessToken) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/AsyncDispatcherTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/AsyncDispatcherTests.swift deleted file mode 100644 index 8c38d240..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/AsyncDispatcherTests.swift +++ /dev/null @@ -1,115 +0,0 @@ -// -// AsyncDispatcherTests.swift -// UberRides -// -// Copyright © 2018 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - - -import XCTest -@testable import UberCore - -class AsyncDispatcherTests: XCTestCase { - - override func setUp() { - super.setUp() - // Put setup code here. This method is called before the invocation of each test method in the class. - } - - override func tearDown() { - // Put teardown code here. This method is called after the invocation of each test method in the class. - super.tearDown() - } - - func testCallsAllClosures() { - let urls: [URL] = [ URL(string: "http://www.google.com")! ] - - let withExp = XCTestExpectation(description: "with closure should be called") - let continueExp = XCTestExpectation(description: "continue closure should be called") - let finallyExp = XCTestExpectation(description: "finally closure should be called") - - var finallyCallCount = 0 - var currentUrlIndex = 0 - - AsyncDispatcher.exec(for: urls, - with: { (url: URL) in - XCTAssertEqual(url, urls[currentUrlIndex]) - currentUrlIndex += 1 - - withExp.fulfill() - }, - asyncMethod: openURLTestMethod(_:completion:), - continue: { (error: NSError?) -> Bool in - continueExp.fulfill() - return true - }, - finally: { - finallyCallCount += 1 - XCTAssertEqual(finallyCallCount, 1) - - finallyExp.fulfill() - }) - - wait(for: [withExp, continueExp, finallyExp], timeout: 0.1) - } - - func testExitsInterationEarly() { - let urls: [URL] = [ URL(string: "http://www.google.com")!, - URL(string: "http://www.uber.com")!, - URL(string: "http://www.facebook.com")! ] - - let finallyExp = XCTestExpectation(description: "finally closure should be called") - - var emittedErrors = [NSError]() - - AsyncDispatcher.exec(for: urls, - with: { _ in }, - asyncMethod: openURLTestMethod(_:completion:), - continue: { (error: NSError?) -> Bool in - if let error = error { - emittedErrors.append(error) - if error.domain == "http://www.uber.com" { - return false - } - } - return true - }, - finally: { - finallyExp.fulfill() - }) - - wait(for: [finallyExp], timeout: 0.1) - - let expectedErrors = [ NSError(domain: "http://www.google.com", code: 0, userInfo: nil), - NSError(domain: "http://www.uber.com", code: 0, userInfo: nil) ] - - XCTAssertEqual(emittedErrors, expectedErrors) - } - - // MARK: - Test helpers - - func openURLTestMethod(_ url: URL, completion: ((NSError?) -> Void)?) { - DispatchQueue.main.async { - let error = NSError(domain: url.absoluteString, code: 0, userInfo: nil) - completion?(error); - } - } - -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/AuthenticationURLUtilityTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/AuthenticationURLUtilityTests.swift deleted file mode 100644 index 9f7768a4..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/AuthenticationURLUtilityTests.swift +++ /dev/null @@ -1,107 +0,0 @@ -// -// AuthenticationURLUtilityTests.swift -// UberRides -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest - -@testable import UberCore - -class AuthenticationURLUtilityTests: XCTestCase { - - private var versionNumber: String? - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - versionNumber = Bundle(for: AuthenticationURLUtility.self).object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String - } - - override func tearDown() { - Configuration.restoreDefaults() - super.tearDown() - } - - func testBuildQueryParameters_withSingleScope() { - - let scopes = [UberScope.rideWidgets] - - let expectedScopes = scopes.toUberScopeString() - let expectedClientID = "testClientID" - let expectedAppName = "My Awesome App" - let expectedCallbackURI = "testURI://uberConnectNative" - let expectedSDK = "ios" - let expectedSDKVersion = versionNumber - - let scopeQueryItem = URLQueryItem(name: AuthenticationURLUtility.scopesKey, value: expectedScopes) - let clientIDQueryItem = URLQueryItem(name: AuthenticationURLUtility.clientIDKey, value: expectedClientID) - let appNameQueryItem = URLQueryItem(name: AuthenticationURLUtility.appNameKey, value: expectedAppName) - let callbackURIQueryItem = URLQueryItem(name: AuthenticationURLUtility.callbackURIKey, value: expectedCallbackURI) - let sdkQueryItem = URLQueryItem(name: AuthenticationURLUtility.sdkKey, value: expectedSDK) - let sdkVersionQueryItem = URLQueryItem(name: AuthenticationURLUtility.sdkVersionKey, value: expectedSDKVersion) - - let expectedQueryItems = [scopeQueryItem, clientIDQueryItem, appNameQueryItem, callbackURIQueryItem, sdkQueryItem, sdkVersionQueryItem] - let comparisonSet = NSSet(array: expectedQueryItems) - - let testQueryItems = AuthenticationURLUtility.buildQueryParameters(scopes: scopes, requestUri: nil) - let testComparisonSet = NSSet(array:testQueryItems) - - XCTAssertEqual(comparisonSet, testComparisonSet) - } - - func testBuildQueryParameters_withMultipleScopes() { - - let scopes = [UberScope.rideWidgets, UberScope.allTrips, UberScope.history] - - let expectedScopes = scopes.toUberScopeString() - let expectedClientID = "testClientID" - let expectedAppName = "My Awesome App" - let expectedCallbackURI = "testURI://uberConnectNative" - let expectedSDK = "ios" - let expectedSDKVersion = versionNumber - - let scopeQueryItem = URLQueryItem(name: AuthenticationURLUtility.scopesKey, value: expectedScopes) - let clientIDQueryItem = URLQueryItem(name: AuthenticationURLUtility.clientIDKey, value: expectedClientID) - let appNameQueryItem = URLQueryItem(name: AuthenticationURLUtility.appNameKey, value: expectedAppName) - let callbackURIQueryItem = URLQueryItem(name: AuthenticationURLUtility.callbackURIKey, value: expectedCallbackURI) - let sdkQueryItem = URLQueryItem(name: AuthenticationURLUtility.sdkKey, value: expectedSDK) - let sdkVersionQueryItem = URLQueryItem(name: AuthenticationURLUtility.sdkVersionKey, value: expectedSDKVersion) - - let expectedQueryItems = [scopeQueryItem, clientIDQueryItem, appNameQueryItem, callbackURIQueryItem, sdkQueryItem, sdkVersionQueryItem] - let comparisonSet = NSSet(array: expectedQueryItems) - - let testQueryItems = AuthenticationURLUtility.buildQueryParameters(scopes: scopes, requestUri: nil) - let testComparisonSet = NSSet(array:testQueryItems) - - XCTAssertEqual(comparisonSet, testComparisonSet) - } - - func testShouldHandleRedirectURL() { - let testRedirectURL = URL(string: "test://handleThis")! - - Configuration.shared.setCallbackURI(testRedirectURL, type: .general) - XCTAssertTrue(AuthenticationURLUtility.shouldHandleRedirectURL(testRedirectURL)) - - Configuration.shared.setCallbackURI(nil, type: .general) - - XCTAssertFalse(AuthenticationURLUtility.shouldHandleRedirectURL(testRedirectURL)) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/BaseAuthenticatorTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/BaseAuthenticatorTests.swift deleted file mode 100644 index ced2076b..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/BaseAuthenticatorTests.swift +++ /dev/null @@ -1,108 +0,0 @@ -// -// BaseAuthenticatorTests.swift -// UberRides -// -// Copyright © 2015 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -@testable import UberCore - -class BaseAuthenticatorTests: XCTestCase { - private var expectation: XCTestExpectation! - private var accessToken: AccessToken? - private var error: NSError? - private let timeout: TimeInterval = 2 - private let tokenString = "accessToken1234" - private var incomingURLComponents: URLComponents? - private var baseAuthenticator = BaseAuthenticator(scopes: []) - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - Configuration.shared.isSandbox = true - incomingURLComponents = URLComponents(url: Configuration.shared.getCallbackURI(for: .general), resolvingAgainstBaseURL: false) - baseAuthenticator = BaseAuthenticator(scopes: []) - } - - override func tearDown() { - _ = TokenManager.deleteToken() - Configuration.restoreDefaults() - super.tearDown() - } - - func testBaseAuthenticator_correctlySavesScopes() { - let scopes = [UberScope.profile, UberScope.allTrips] - baseAuthenticator = BaseAuthenticator(scopes: scopes) - XCTAssertEqual(scopes, baseAuthenticator.scopes); - } - - func testBaseAuthenticatorCreatesAccessTokenFromValidRedirectURL() { - incomingURLComponents?.fragment = "access_token=\(tokenString)" - guard let incomingURL = incomingURLComponents?.url else { - XCTFail("Error setting up test") - return - } - - self.expectation = expectation(description: "The valid token should be parsed") - - baseAuthenticator.consumeResponse(url: incomingURL) { accessToken, error in - XCTAssertEqual(accessToken?.tokenString, self.tokenString) - XCTAssertNil(error) - self.expectation.fulfill() - } - waitForExpectations(timeout: 1, handler: nil) - } - - func testBaseAuthenticatorCreatesErrorFromValidRedirectURL() { - incomingURLComponents?.fragment = "error=invalid_grant&error_description=Invalid%20Password" - guard let incomingURL = incomingURLComponents?.url else { - XCTFail("Error setting up test") - return - } - - self.expectation = expectation(description: "The error should be parsed") - - baseAuthenticator.consumeResponse(url: incomingURL) { accessToken, error in - XCTAssertNil(accessToken) - XCTAssertEqual(error?.domain, "com.uber.rides-ios-sdk.ridesAuthenticationError") - self.expectation.fulfill() - } - waitForExpectations(timeout: 1, handler: nil) - } - - func testBaseAuthenticatorCreatesErrorFromInvalidRedirectURL() { - incomingURLComponents?.fragment = "WOLOLO" - guard let incomingURL = incomingURLComponents?.url else { - XCTFail("Error setting up test") - return - } - - self.expectation = expectation(description: "The invalid response should result in an error.") - - baseAuthenticator.consumeResponse(url: incomingURL) { accessToken, error in - XCTAssertNil(accessToken) - XCTAssertEqual(error, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .invalidResponse)) - self.expectation.fulfill() - } - waitForExpectations(timeout: 1, handler: nil) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/BaseDeeplinkTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/BaseDeeplinkTests.swift index c46f6810..49d723a1 100644 --- a/examples/Swift SDK/Swift SDKTests/UberCore/BaseDeeplinkTests.swift +++ b/examples/Swift SDK/Swift SDKTests/UberCore/BaseDeeplinkTests.swift @@ -22,7 +22,9 @@ import XCTest +@testable import UberAuth @testable import UberCore +@testable import UberRides class BaseDeeplinkTests: XCTestCase { diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/ConfigurationTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/ConfigurationTests.swift deleted file mode 100644 index 265c498d..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/ConfigurationTests.swift +++ /dev/null @@ -1,270 +0,0 @@ -// -// ConfigurationTests.swift -// UberRides -// -// Copyright © 2015 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -@testable import UberCore - -class ConfigurationTests: XCTestCase { - - private let defaultClientID = "testClientID" - private let defaultDisplayName = "My Awesome App" - private let defaultCallback = URL(string: "testURI://uberConnect")! - private let defaultGeneralCallback = URL(string: "testURI://uberConnectGeneral")! - private let defaultAuthorizationCodeCallback = URL(string: "testURI://uberConnectAuthorizationCode")! - private let defaultImplicitCallback = URL(string: "testURI://uberConnectImplicit")! - private let defaultNativeCallback = URL(string: "testURI://uberConnectNative")! - private let defaultServerToken = "testServerToken" - private let defaultAccessTokenIdentifier = "RidesAccessTokenKey" - private let defaultSandbox = false - - override func setUp() { - super.setUp() - Configuration.bundle = Bundle.main - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - } - - override func tearDown() { - Configuration.restoreDefaults() - super.tearDown() - } - - //MARK: Reset Test - - func testConfiguration_restoreDefaults() { - - let newClientID = "newID" - let newCallback = URL(string: "newCallback://")! - let newDisplay = "newDisplay://" - let newServerToken = "newserver" - let newGroup = "new group" - let newTokenId = "newTokenID" - let newSandbox = true - - Configuration.shared.clientID = newClientID - Configuration.shared.setCallbackURI(newCallback) - Configuration.shared.appDisplayName = newDisplay - Configuration.shared.serverToken = newServerToken - Configuration.shared.defaultKeychainAccessGroup = newGroup - Configuration.shared.defaultAccessTokenIdentifier = newTokenId - Configuration.shared.isSandbox = newSandbox - - XCTAssertEqual(newClientID, Configuration.shared.clientID) - XCTAssertEqual(newCallback, Configuration.shared.getCallbackURI()) - XCTAssertEqual(newDisplay, Configuration.shared.appDisplayName) - XCTAssertEqual(newServerToken, Configuration.shared.serverToken) - XCTAssertEqual(newGroup, Configuration.shared.defaultKeychainAccessGroup) - XCTAssertEqual(newTokenId, Configuration.shared.defaultAccessTokenIdentifier) - XCTAssertEqual(newSandbox, Configuration.shared.isSandbox) - Configuration.restoreDefaults() - - Configuration.plistName = "testInfo" - Configuration.bundle = Bundle.main - - XCTAssertEqual(Configuration.shared.clientID, defaultClientID) - XCTAssertEqual(defaultGeneralCallback, Configuration.shared.getCallbackURI()) - XCTAssertEqual(defaultDisplayName, Configuration.shared.appDisplayName) - XCTAssertEqual(defaultServerToken, Configuration.shared.serverToken) - XCTAssertEqual("", Configuration.shared.defaultKeychainAccessGroup) - XCTAssertEqual(defaultAccessTokenIdentifier, Configuration.shared.defaultAccessTokenIdentifier) - XCTAssertEqual(defaultSandbox, Configuration.shared.isSandbox) - } - - //MARK: Client ID Tests - - func testClientID_getDefault() { - XCTAssertEqual(defaultClientID, Configuration.shared.clientID) - } - - func testClientID_overwriteDefault() { - let clientID = "clientID" - Configuration.shared.clientID = clientID - XCTAssertEqual(clientID, Configuration.shared.clientID) - } - - //MARK: Callback URI String Tests - - func testCallbackURI_getDefault() { - XCTAssertEqual(defaultGeneralCallback, Configuration.shared.getCallbackURI()) - } - - func testCallbackURI_overwriteDefault() { - let callbackURI = URL(string: "callback://test")! - Configuration.shared.setCallbackURI(callbackURI) - - XCTAssertEqual(callbackURI, Configuration.shared.getCallbackURI()) - } - - func testCallbackURI_getDefault_getTypes() { - XCTAssertEqual(defaultGeneralCallback, Configuration.shared.getCallbackURI(for: .general)) - XCTAssertEqual(defaultAuthorizationCodeCallback, Configuration.shared.getCallbackURI(for: .authorizationCode)) - XCTAssertEqual(defaultImplicitCallback, Configuration.shared.getCallbackURI(for: .implicit)) - XCTAssertEqual(defaultNativeCallback, Configuration.shared.getCallbackURI(for: .native)) - } - - func testCallbackURI_overwriteDefault_allTypes() { - let generalCallback = URL(string: "testURI://uberConnectGeneralNew")! - let authorizationCodeCallback = URL(string: "testURI://uberConnectAuthorizationCodeNew")! - let implicitCallback = URL(string: "testURI://uberConnectImplicitNew")! - let nativeCallback = URL(string: "testURI://uberConnectNativeNew")! - - Configuration.shared.setCallbackURI(generalCallback, type: .general) - Configuration.shared.setCallbackURI(authorizationCodeCallback, type: .authorizationCode) - Configuration.shared.setCallbackURI(implicitCallback, type: .implicit) - Configuration.shared.setCallbackURI(nativeCallback, type: .native) - - XCTAssertEqual(generalCallback, Configuration.shared.getCallbackURI(for: .general)) - XCTAssertEqual(authorizationCodeCallback, Configuration.shared.getCallbackURI(for: .authorizationCode)) - XCTAssertEqual(implicitCallback, Configuration.shared.getCallbackURI(for: .implicit)) - XCTAssertEqual(nativeCallback, Configuration.shared.getCallbackURI(for: .native)) - } - - func testCallbackURI_resetDefault_allTypes() { - let generalCallback = URL(string: "testURI://uberConnectGeneralNew")! - let authorizationCodeCallback = URL(string: "testURI://uberConnectAuthorizationCodeNew")! - let implicitCallback = URL(string: "testURI://uberConnectImplicitNew")! - let nativeCallback = URL(string: "testURI://uberConnectNativeNew")! - - Configuration.shared.setCallbackURI(generalCallback, type: .general) - Configuration.shared.setCallbackURI(authorizationCodeCallback, type: .authorizationCode) - Configuration.shared.setCallbackURI(implicitCallback, type: .implicit) - Configuration.shared.setCallbackURI(nativeCallback, type: .native) - - Configuration.shared.setCallbackURI(nil, type: .general) - Configuration.shared.setCallbackURI(nil, type: .authorizationCode) - Configuration.shared.setCallbackURI(nil, type: .implicit) - Configuration.shared.setCallbackURI(nil, type: .native) - - XCTAssertEqual(defaultGeneralCallback, Configuration.shared.getCallbackURI(for: .general)) - XCTAssertEqual(defaultAuthorizationCodeCallback, Configuration.shared.getCallbackURI(for: .authorizationCode)) - XCTAssertEqual(defaultImplicitCallback, Configuration.shared.getCallbackURI(for: .implicit)) - XCTAssertEqual(defaultNativeCallback, Configuration.shared.getCallbackURI(for: .native)) - } - - func testCallbackURI_resetDefault_oneType() { - let generalCallback = URL(string: "testURI://uberConnectGeneralNew")! - let authorizationCodeCallback = URL(string: "testURI://uberConnectAuthorizationCodeNew")! - let implicitCallback = URL(string: "testURI://uberConnectImplicitNew")! - let nativeCallback = URL(string: "testURI://uberConnectNativeNew")! - - Configuration.shared.setCallbackURI(generalCallback, type: .general) - Configuration.shared.setCallbackURI(authorizationCodeCallback, type: .authorizationCode) - Configuration.shared.setCallbackURI(implicitCallback, type: .implicit) - Configuration.shared.setCallbackURI(nativeCallback, type: .native) - - Configuration.shared.setCallbackURI(nil, type: .native) - - XCTAssertEqual(generalCallback, Configuration.shared.getCallbackURI(for: .general)) - XCTAssertEqual(authorizationCodeCallback, Configuration.shared.getCallbackURI(for: .authorizationCode)) - XCTAssertEqual(implicitCallback, Configuration.shared.getCallbackURI(for: .implicit)) - XCTAssertEqual(defaultNativeCallback, Configuration.shared.getCallbackURI(for: .native)) - } - - func testCallbackURIFallback_whenCallbackURIsMissing() { - Configuration.bundle = Bundle(for: Configuration.self) - Configuration.plistName = "testInfoMissingCallbacks" - Configuration.restoreDefaults() - XCTAssertEqual(defaultCallback, Configuration.shared.getCallbackURI(for: .general)) - XCTAssertEqual(defaultCallback, Configuration.shared.getCallbackURI(for: .authorizationCode)) - XCTAssertEqual(defaultCallback, Configuration.shared.getCallbackURI(for: .implicit)) - XCTAssertEqual(defaultCallback, Configuration.shared.getCallbackURI(for: .native)) - } - - func testCallbackURIFallbackUsesGeneralOverride_whenCallbackURIsMissing() { - Configuration.bundle = Bundle(for: Configuration.self) - Configuration.plistName = "testInfoMissingCallbacks" - Configuration.restoreDefaults() - let override = URL(string: "testURI://override")! - Configuration.shared.setCallbackURI(override, type: .general) - XCTAssertEqual(override, Configuration.shared.getCallbackURI(for: .general)) - XCTAssertEqual(override, Configuration.shared.getCallbackURI(for: .authorizationCode)) - XCTAssertEqual(override, Configuration.shared.getCallbackURI(for: .implicit)) - XCTAssertEqual(override, Configuration.shared.getCallbackURI(for: .native)) - } - - //MARK: App Display Name Tests - - func testAppDisplayName_getDefault() { - XCTAssertEqual(defaultDisplayName, Configuration.shared.appDisplayName) - } - - func testAppDisplayName_overwriteDefault() { - let appDisplayName = "Test App" - Configuration.shared.appDisplayName = appDisplayName - - XCTAssertEqual(appDisplayName, Configuration.shared.appDisplayName) - } - - //MARK: Server Token Tests - - func testServerToken_getDefault() { - XCTAssertEqual(defaultServerToken, Configuration.shared.serverToken) - } - - func testServerToken_overwriteDefault() { - let serverToken = "nonDefaultToken" - Configuration.shared.serverToken = serverToken - - XCTAssertEqual(serverToken, Configuration.shared.serverToken) - } - - //MARK: Keychain Access Group Tests - - func testDefaultKeychainAccessGroup_getDefault() { - XCTAssertEqual("", Configuration.shared.defaultKeychainAccessGroup) - } - - func testDefaultKeychainAccessGroup_overwriteDefault() { - let defaultKeychainAccessGroup = "accessGroup" - Configuration.shared.defaultKeychainAccessGroup = defaultKeychainAccessGroup - - XCTAssertEqual(defaultKeychainAccessGroup, Configuration.shared.defaultKeychainAccessGroup) - } - - //MARK: Access token identifier tests - - func testDefaultAccessTokenIdentifier_getDefault() { - XCTAssertEqual(defaultAccessTokenIdentifier, Configuration.shared.defaultAccessTokenIdentifier) - } - - func testDefaultAccessTokenIdentifier_overwriteDefault() { - let newIdentifier = "newIdentifier" - Configuration.shared.defaultAccessTokenIdentifier = newIdentifier - - XCTAssertEqual(newIdentifier, Configuration.shared.defaultAccessTokenIdentifier) - } - - //MARK: Sandbox Tests - - func testSandbox_getDefault() { - XCTAssertEqual(defaultSandbox, Configuration.shared.isSandbox) - } - - func testSandbox_overwriteDefault() { - let newSandbox = true - Configuration.shared.isSandbox = newSandbox - - XCTAssertEqual(newSandbox, Configuration.shared.isSandbox) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/DeeplinkErrorFactoryTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/DeeplinkErrorFactoryTests.swift deleted file mode 100644 index f7136db7..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/DeeplinkErrorFactoryTests.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// DeeplinkErrorFactoryTests.swift -// UberRides -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -@testable import UberCore - -class DeeplinkErrorFactoryTests: XCTestCase { - let expectedErrorToValueMapping = [ - DeeplinkErrorType.deeplinkNotFollowed : DeeplinkErrorType.deeplinkNotFollowed.rawValue, - DeeplinkErrorType.unableToFollow : DeeplinkErrorType.unableToFollow.rawValue, - DeeplinkErrorType.unableToOpen : DeeplinkErrorType.unableToOpen.rawValue, - ] - - func testCreateErrorsByErrorType() { - - for errorType in expectedErrorToValueMapping.keys { - let deeplinkError = DeeplinkErrorFactory.errorForType(errorType) - - XCTAssertNotNil(deeplinkError) - XCTAssertEqual(deeplinkError.code , errorType.rawValue) - XCTAssertEqual(deeplinkError.domain , DeeplinkErrorFactory.errorDomain) - } - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/DeeplinkManagerTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/DeeplinkManagerTests.swift index 35ce4fdf..70aa1bdf 100644 --- a/examples/Swift SDK/Swift SDKTests/UberCore/DeeplinkManagerTests.swift +++ b/examples/Swift SDK/Swift SDKTests/UberCore/DeeplinkManagerTests.swift @@ -8,6 +8,7 @@ import XCTest @testable import UberCore +@testable import UberRides class DeeplinkManagerTests: XCTestCase { private var deeplinkManager: DeeplinkManager! diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/LoginButtonTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/LoginButtonTests.swift deleted file mode 100644 index 2f2f53d6..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/LoginButtonTests.swift +++ /dev/null @@ -1,161 +0,0 @@ -// -// LoginButtonTests.swift -// UberRides -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -import CoreLocation -@testable import UberCore - -class LoginButtonTests : XCTestCase { - - private var keychain: KeychainWrapper! - private var testToken: AccessToken! - private var testDataSource: TestDataSource! - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - Configuration.shared.isSandbox = true - keychain = KeychainWrapper() - testToken = AccessToken(tokenString: "testTokenString") - } - - override func tearDown() { - Configuration.restoreDefaults() - keychain = nil - super.tearDown() - } - - func testButtonState_whenSignedOut() { - let identifier = "testIdentifier" - - _ = keychain.deleteObjectForKey(identifier) - - let token = TokenManager.fetchToken(identifier: identifier) - XCTAssertNil(token) - - let loginManager = LoginManager(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit) - let loginButton = LoginButton(frame: CGRect.zero, scopes: [], loginManager: loginManager) - - XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedOut) - - _ = keychain.deleteObjectForKey(identifier) - } - - func testLabelText_whenSignedIn() { - let identifier = "testIdentifier" - - let token: AccessToken = testToken - - XCTAssertTrue(keychain.setObject(token, key: identifier)) - - let loginManager = LoginManager(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit) - let loginButton = LoginButton(frame: CGRect.zero, scopes: [], loginManager: loginManager) - - XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedIn) - - XCTAssertTrue(keychain.deleteObjectForKey(identifier)) - } - - func testLoginCalled_whenSignedOut() { - let identifier = "testIdentifier" - - _ = keychain.deleteObjectForKey(identifier) - - let token = TokenManager.fetchToken(identifier: identifier) - XCTAssertNil(token) - - let expectation = self.expectation(description: "Expected executeLogin() called") - - let loginManager = LoginManagerPartialMock(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit) - loginManager.executeLoginClosure = { _ in - expectation.fulfill() - } - let loginButton = LoginButton(frame: CGRect.zero, scopes: [.profile], loginManager: loginManager) - - loginButton.presentingViewController = UIViewController() - XCTAssertNotNil(loginButton) - XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedOut) - loginButton.uberButtonTapped(loginButton) - - waitForExpectations(timeout: 0.2) { _ in - _ = self.keychain.deleteObjectForKey(identifier) - } - } - - func testLogOut_whenSignedIn() { - let identifier = "testIdentifier" - - _ = keychain.deleteObjectForKey(identifier) - - let token: AccessToken = testToken - - XCTAssertTrue(keychain.setObject(token, key: identifier)) - - let loginManager = LoginManager(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit) - let loginButton = LoginButton(frame: CGRect.zero, scopes: [.profile], loginManager: loginManager) - - loginButton.presentingViewController = UIViewController() - XCTAssertNotNil(loginButton) - XCTAssertEqual(loginButton.buttonState, LoginButtonState.signedIn) - loginButton.uberButtonTapped(loginButton) - - XCTAssertNil(TokenManager.fetchToken(identifier: identifier)) - - _ = keychain.deleteObjectForKey(identifier) - } - - func test_loginButton_callsDataSourceOnTap() { - let identifier = "testIdentifier" - - let loginManager = LoginManager(accessTokenIdentifier: identifier, keychainAccessGroup: nil, loginType: .implicit) - let loginButton = LoginButton(frame: CGRect.zero, scopes: [.profile], loginManager: loginManager) - - let expectation = self.expectation(description: "Prefill handler called") - - let prefillHandler: () -> Prefill? = { - expectation.fulfill() - return nil - } - - testDataSource = TestDataSource(prefillHandler) - loginButton.dataSource = testDataSource - loginButton.uberButtonTapped(loginButton) - - waitForExpectations(timeout: 0.2) - } - - // MARK: - TestDataSource - - fileprivate class TestDataSource: LoginButtonDataSource { - - private let prefillValueHandler: () -> Prefill? - - init(_ prefillValueHandler: @escaping () -> Prefill?) { - self.prefillValueHandler = prefillValueHandler - } - - func prefillValues(_ button: LoginButton) -> Prefill? { - prefillValueHandler() - } - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/LoginManagerTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/LoginManagerTests.swift deleted file mode 100644 index bac1dc51..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/LoginManagerTests.swift +++ /dev/null @@ -1,397 +0,0 @@ -// -// LoginManagerTests.swift -// UberRides -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -import CoreLocation -import OHHTTPStubs -import OHHTTPStubsSwift -import WebKit -@testable import UberCore - -class LoginManagerTests: XCTestCase { - private let timeout: Double = 2 - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - Configuration.shared.isSandbox = true - } - - override func tearDown() { - Configuration.restoreDefaults() - super.tearDown() - } - - func testRidesAppDelegateContainsManager_afterNativeLogin() { - let loginManager = LoginManager(loginType: .native) - - loginManager.login(requestedScopes: [.profile], presentingViewController: nil, completion: nil) - - XCTAssert(UberAppDelegate.shared.loginManager is LoginManager, "Expected RidesAppDelegate to have loginManager instance") - } - - func testAuthentictorIsImplicit_whenLoginWithImplicitType() { - let loginManager = LoginManager(loginType: .implicit) - - let presentingViewController = UIViewController() - - loginManager.login(requestedScopes: [.profile], presentingViewController: presentingViewController, completion: nil) - - XCTAssert(loginManager.authenticator is ImplicitGrantAuthenticator) - XCTAssertTrue(loginManager.loggingIn) - } - - func testAuthentictorIsAuthorizationCode_whenLoginWithAuthorizationCodeType() { - let loginManager = LoginManager(loginType: .authorizationCode) - - let presentingViewController = UIViewController() - - loginManager.login(requestedScopes: [.profile], presentingViewController: presentingViewController, completion: nil) - - XCTAssert(loginManager.authenticator is AuthorizationCodeGrantAuthenticator) - XCTAssertTrue(loginManager.loggingIn) - } - - func testLoginFails_whenLoggingIn() { - let expectation = self.expectation(description: "loginCompletion called") - - let loginCompletion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void) = { token, error in - guard let error = error else { - XCTFail() - return - } - XCTAssertEqual(error.code, UberAuthenticationErrorType.unavailable.rawValue) - expectation.fulfill() - } - - let loginManagerMock = LoginManagerPartialMock() - loginManagerMock.executeLoginClosure = { completionHandler in - completionHandler?(nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) - } - - loginManagerMock.login(requestedScopes: [.profile], presentingViewController: nil, prefillValues: nil, completion: loginCompletion) - - waitForExpectations(timeout: 0.2, handler: nil) - } - - func testOpenURLFails_whenInvalidSource() { - let loginManager = LoginManager(loginType: .native) - let testApp = UIApplication.shared - guard let testURL = URL(string: "http://www.google.com") else { - XCTFail() - return - } - let testSourceApplication = "com.not.uber.app" - let testAnnotation = "annotation" - - XCTAssertFalse(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) - } - - func testOpenURLFails_whenNotNativeType() { - let loginManager = LoginManager(loginType: .implicit) - let testApp = UIApplication.shared - guard let testURL = URL(string: "http://www.google.com") else { - XCTFail() - return - } - let testSourceApplication = "com.ubercab.foo" - let testAnnotation = "annotation" - - XCTAssertFalse(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) - } - - func testOpenURLSuccess_rides() { - let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)]) - let testApp = UIApplication.shared - guard let testURL = URL(string: "http://www.google.com") else { - XCTFail() - return - } - let testSourceApplication = "com.ubercab.foo" - let testAnnotation = "annotation" - - let authenticatorMock = RidesNativeAuthenticatorPartialStub(scopes: [.profile]) - authenticatorMock.consumeResponseCompletionValue = (nil, nil) - loginManager.authenticator = authenticatorMock - loginManager.loggingIn = true - - XCTAssertTrue(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) - - XCTAssertFalse(loginManager.loggingIn) - XCTAssertNil(loginManager.authenticator) - } - - func testOpenURLSuccess_eats() { - let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)]) - let testApp = UIApplication.shared - guard let testURL = URL(string: "http://www.google.com") else { - XCTFail() - return - } - let testSourceApplication = "com.ubercab.UberEats" - let testAnnotation = "annotation" - - let authenticatorMock = EatsNativeAuthenticatorPartialStub(scopes: [.profile]) - authenticatorMock.consumeResponseCompletionValue = (nil, nil) - loginManager.authenticator = authenticatorMock - loginManager.loggingIn = true - - XCTAssertTrue(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) - - XCTAssertFalse(loginManager.loggingIn) - XCTAssertNil(loginManager.authenticator) - } - - func testCancelLoginNotCalled_whenNotEnteringForeground() { - let loginManager = LoginManager(loginType: .native) - loginManager.loggingIn = true - - loginManager.applicationDidBecomeActive() - - XCTAssertNil(loginManager.authenticator) - XCTAssertTrue(loginManager.loggingIn) - } - - func testCancelLoginCalled_whenDidBecomeActive() { - let loginManager = LoginManager(loginType: .native) - loginManager.loggingIn = true - - loginManager.applicationWillEnterForeground() - loginManager.applicationDidBecomeActive() - - XCTAssertNil(loginManager.authenticator) - XCTAssertFalse(loginManager.loggingIn) - } - - func testNativeLoginCompletionDoesFallback_whenUnavailableError_withConfiguration_alwaysUseAuthCodeFallback() { - Configuration.shared.alwaysUseAuthCodeFallback = true - let scopes = [UberScope.historyLite] - - let loginManager = LoginManager(loginType: .native) - - let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: []) - nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) - - loginManager.authenticator = nativeAuthenticatorStub - - let viewController = UIViewController() - - loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) - - XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode) - } - - func testNativeLoginCompletionDoesFallback_whenUnavailableError_withPrivelegedScopes_rides() { - Configuration.shared.useFallback = true - let scopes = [UberScope.request] - - let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)]) - - let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: []) - nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) - - loginManager.authenticator = nativeAuthenticatorStub - - let viewController = UIViewController() - - loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) - - XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode) - } - - func testNativeLoginCompletionDoesFallback_whenUnavailableError_withPrivelegedScopes_eats() { - Configuration.shared.useFallback = true - let scopes = [UberScope.request] - - let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)]) - - let nativeAuthenticatorStub = EatsNativeAuthenticatorPartialStub(scopes: []) - nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) - - loginManager.authenticator = nativeAuthenticatorStub - - let viewController = UIViewController() - - loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) - - XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode) - } - - func testNativeLoginCompletionDoesFallback_whenUnavailableError_withGeneralScopes_rides() { - let scopes = [UberScope.profile] - - let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)]) - - let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: []) - nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) - - loginManager.authenticator = nativeAuthenticatorStub - - let viewController = UIViewController() - - loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) - - XCTAssertEqual(loginManager.loginType, LoginType.implicit) - } - - func testNativeLoginCompletionDoesFallback_whenUnavailableError_withGeneralScopes_eats() { - let scopes = [UberScope.profile] - - let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)]) - - let nativeAuthenticatorStub = EatsNativeAuthenticatorPartialStub(scopes: []) - nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable)) - - loginManager.authenticator = nativeAuthenticatorStub - - let viewController = UIViewController() - - loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil) - - XCTAssertEqual(loginManager.loginType, LoginType.implicit) - } - - func testImplicitLogin_executesParRequest() { - - let expectation = expectation(description: "Implicit login PAR endpoint called") - - stub(condition: isPath("/oauth/v2/par")) { _ in - expectation.fulfill() - return HTTPStubsResponse() - } - - let loginManager = LoginManager( - loginType: .implicit, - productFlowPriority: [UberAuthenticationProductFlow(.eats)] - ) - - loginManager.login( - requestedScopes: [UberScope.profile], - presentingViewController: UIViewController(), - prefillValues: Prefill(email: "test@test.com"), - completion: nil - ) - - waitForExpectations(timeout: 0.2, handler: nil) - } - - func testAuthorizationCodeLogin_executesParRequest() { - - let expectation = expectation(description: "Authorization code login PAR endpoint called") - - stub(condition: isPath("/oauth/v2/par")) { _ in - expectation.fulfill() - return HTTPStubsResponse() - } - - let loginManager = LoginManager( - loginType: .authorizationCode, - productFlowPriority: [UberAuthenticationProductFlow(.eats)] - ) - - loginManager.login( - requestedScopes: [UberScope.profile], - presentingViewController: UIViewController(), - prefillValues: Prefill(email: "test@test.com"), - completion: nil - ) - - waitForExpectations(timeout: 0.2, handler: nil) - } - - func testLogin_withNoPrefillValues_doesNotExecutesParRequest() { - - let expectation = expectation(description: "No prefill login PAR endpoint not called") - expectation.isInverted = true - - stub(condition: isPath("/oauth/v2/par")) { _ in - expectation.fulfill() - return HTTPStubsResponse() - } - - let loginManager = LoginManager( - loginType: .authorizationCode, - productFlowPriority: [UberAuthenticationProductFlow(.eats)] - ) - - loginManager.login( - requestedScopes: [UberScope.profile], - presentingViewController: UIViewController(), - prefillValues: nil, - completion: nil - ) - - waitForExpectations(timeout: 0.2, handler: nil) - } - - func testLogin_withEmptyPrefillValues_doesNotExecutesParRequest() { - - let expectation = expectation(description: "EmptyPrefill login PAR endpoint not called") - expectation.isInverted = true - - stub(condition: isPath("/oauth/v2/par")) { _ in - expectation.fulfill() - return HTTPStubsResponse() - } - - let loginManager = LoginManager( - loginType: .authorizationCode, - productFlowPriority: [UberAuthenticationProductFlow(.eats)] - ) - - loginManager.login( - requestedScopes: [UberScope.profile], - presentingViewController: UIViewController(), - prefillValues: Prefill(), - completion: nil - ) - - waitForExpectations(timeout: 0.2, handler: nil) - } - - func testNativeLogin_doesNotExecuteParRequest() { - - let expectation = expectation(description: "Native login PAR endpoint not called") - expectation.isInverted = true - - stub(condition: isPath("/oauth/v2/par")) { _ in - expectation.fulfill() - return HTTPStubsResponse() - } - - let loginManager = LoginManager( - loginType: .native, - productFlowPriority: [UberAuthenticationProductFlow(.eats)] - ) - - loginManager.login( - requestedScopes: [UberScope.profile], - presentingViewController: UIViewController(), - prefillValues: Prefill(), - completion: nil - ) - - waitForExpectations(timeout: 0.2, handler: nil) - } -} - diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/OAuthTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/OAuthTests.swift deleted file mode 100644 index b61f9293..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/OAuthTests.swift +++ /dev/null @@ -1,177 +0,0 @@ -// -// OAuthTests.swift -// UberRidesTests -// -// Copyright © 2015 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -@testable import UberCore - -class OAuthTests: XCTestCase { - var testExpectation: XCTestExpectation! - var accessToken: AccessToken? - var error: NSError? - let timeout: TimeInterval = 2 - let tokenString = "accessToken1234" - let refreshTokenString = "refresh" - let tokenTypeString = "type" - let expiresIn = 10030.23 - let scope = "profile history" - - private var redirectURI: URL! - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - Configuration.shared.isSandbox = true - redirectURI = Configuration.shared.getCallbackURI() - } - - override func tearDown() { - _ = TokenManager.deleteToken() - Configuration.restoreDefaults() - super.tearDown() - } - - /** - Test saving and object in keychain and retrieving it. - */ - func testSaveRetrieveObjectFromKeychain() { - guard let token = tokenFixture() else { - XCTAssert(false) - return - } - - let keychain = KeychainWrapper() - let key = "AccessTokenKey" - XCTAssertTrue(keychain.setObject(token, key: key)) - - let result = keychain.getObjectForKey(key) as! AccessToken - XCTAssertEqual(result.tokenString, token.tokenString) - XCTAssertEqual(result.refreshToken, token.refreshToken) - XCTAssertEqual(result.tokenType, token.tokenType) - XCTAssertEqual(result.grantedScopes, token.grantedScopes) - - XCTAssertTrue(keychain.deleteObjectForKey(key)) - - // Make sure object was actually deleted - XCTAssertNil(keychain.getObjectForKey(key)) - } - - /** - Test saving a duplicate key with different value and verify that value is updated. - */ - func testSaveDuplicateObjectInKeychain() { - guard let token = tokenFixture(), let newToken = tokenFixture("newTokenString") else { - XCTAssert(false) - return - } - - let keychain = KeychainWrapper() - let key = "AccessTokenKey" - XCTAssertTrue(keychain.setObject(token, key: key)) - - XCTAssertTrue(keychain.setObject(newToken, key: key)) - - let result = keychain.getObjectForKey(key) as! AccessToken - XCTAssertEqual(result.tokenString, newToken.tokenString) - XCTAssertEqual(result.refreshToken, newToken.refreshToken) - XCTAssertEqual(result.tokenType, newToken.tokenType) - XCTAssertEqual(result.grantedScopes, newToken.grantedScopes) - - XCTAssertTrue(keychain.deleteObjectForKey(key)) - - // Make sure object was actually deleted - XCTAssertNil(keychain.getObjectForKey(key)) - } - - /** - Test that endpoint has correct query - */ - func testImplicitGrantAuthenticator_withScopes_returnsCorrectEndpoint() { - redirectURI = Configuration.shared.getCallbackURI(for: .implicit) - let scopes = [UberScope.profile] - let expectedPath = "/oauth/v2/authorize" - let implicitGrantBehavior = ImplicitGrantAuthenticator(scopes: scopes) - - guard let queryItems = URLComponents(url: implicitGrantBehavior.authorizationURL, resolvingAgainstBaseURL: false)?.queryItems else { - XCTFail() - return - } - - XCTAssertEqual(implicitGrantBehavior.authorizationURL.path, expectedPath) - XCTAssert(queryItems.contains(URLQueryItem(name: "scope", value: "profile"))) - XCTAssert(queryItems.contains(URLQueryItem(name: "client_id", value: "testClientID"))) - XCTAssert(queryItems.contains(URLQueryItem(name: "redirect_uri", value: redirectURI.absoluteString))) - } - - func testInitializeAccessTokenFromString() { - let token = AccessToken(tokenString: tokenString) - XCTAssertEqual(token.tokenString, tokenString) - } - - func testInitializeAccessTokenFromOAuthDictionary() { - guard let token = tokenFixture() else { - XCTFail() - return - } - XCTAssertEqual(token.tokenString, tokenString) - XCTAssertEqual(token.refreshToken, refreshTokenString) - XCTAssertEqual(token.tokenType, tokenTypeString) - UBSDKAssert(date: token.expirationDate!, approximatelyIn: expiresIn) - XCTAssert(token.grantedScopes.contains(UberScope.profile)) - XCTAssert(token.grantedScopes.contains(UberScope.history)) - } - - func loginCompletion() -> ((_ accessToken: AccessToken?, _ error: NSError?) -> Void) { - return { token, error in - self.accessToken = token - self.error = error - self.testExpectation.fulfill() - } - } - - // Mark: Helper - - func tokenFixture(_ accessToken: String = "accessToken1234") -> AccessToken? - { - var jsonDictionary = [String: Any]() - jsonDictionary["access_token"] = accessToken - jsonDictionary["refresh_token"] = refreshTokenString - jsonDictionary["token_type"] = tokenTypeString - jsonDictionary["expires_in"] = expiresIn - jsonDictionary["scope"] = scope - return AccessToken(oauthDictionary: jsonDictionary) - } -} - -extension XCTestCase { - func UBSDKAssert(date: Date, approximatelyEqualTo otherDate: Date, _ message: String = "") { - let allowedDifference: TimeInterval = 2 - let difference = abs(date.timeIntervalSince(otherDate)) - XCTAssert(difference < allowedDifference, message) - } - - func UBSDKAssert(date: Date, approximatelyIn seconds: TimeInterval, _ message: String = "") { - UBSDKAssert(date: date, approximatelyEqualTo: Date(timeIntervalSinceNow: seconds), message) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/OauthEndpointTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/OauthEndpointTests.swift deleted file mode 100644 index dffba3ec..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/OauthEndpointTests.swift +++ /dev/null @@ -1,179 +0,0 @@ -// -// OauthEndpointTests.swift -// UberRides -// -// Copyright © 2015 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -@testable import UberCore - -class OauthEndpointTests: XCTestCase { - - // {redirect_to_login:true} - let base64EncodedSignup = "eyJyZWRpcmVjdF90b19sb2dpbiI6dHJ1ZX0=" - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - } - - override func tearDown() { - Configuration.restoreDefaults() - super.tearDown() - } - - func testLogin_withSandboxEnabled() { - Configuration.shared.isSandbox = true - - let scopes = [ UberScope.profile, UberScope.history ] - let expectedHost = "https://auth.uber.com" - let expectedPath = "/oauth/v2/authorize" - let expectedScopes = scopes.toUberScopeString() - let expectedClientID = Configuration.shared.clientID - let expectedRedirect = Configuration.shared.getCallbackURI() - let expectedTokenType = "token" - - let expectedQueryItems = [ - URLQueryItem(name: "scope", value: expectedScopes), - URLQueryItem(name: "client_id", value: expectedClientID), - URLQueryItem(name: "redirect_uri", value: expectedRedirect.absoluteString), - URLQueryItem(name: "signup_params", value: base64EncodedSignup), - URLQueryItem(name: "response_type", value: expectedTokenType)] - - let login = OAuth.implicitLogin(clientID: expectedClientID, scopes: scopes, redirect: expectedRedirect) - - XCTAssertEqual(login.host, expectedHost) - XCTAssertEqual(login.path, expectedPath) - XCTAssertEqual(login.query, expectedQueryItems) - } - - func testLogin_withSandboxDisabled() { - Configuration.shared.isSandbox = false - - let scopes = [ UberScope.profile, UberScope.history ] - let expectedHost = "https://auth.uber.com" - let expectedPath = "/oauth/v2/authorize" - let expectedScopes = scopes.toUberScopeString() - let expectedClientID = Configuration.shared.clientID - let expectedRedirect = Configuration.shared.getCallbackURI() - let expectedTokenType = "token" - - let expectedQueryItems = [ - URLQueryItem(name: "scope", value: expectedScopes), - URLQueryItem(name: "client_id", value: expectedClientID), - URLQueryItem(name: "redirect_uri", value: expectedRedirect.absoluteString), - URLQueryItem(name: "signup_params", value: base64EncodedSignup), - URLQueryItem(name: "response_type", value: expectedTokenType)] - - let login = OAuth.implicitLogin(clientID: expectedClientID, scopes: scopes, redirect: expectedRedirect) - - XCTAssertEqual(login.host, expectedHost) - XCTAssertEqual(login.path, expectedPath) - XCTAssertEqual(login.query, expectedQueryItems) - } - - func testLogin_forAuthorizationCodeGrant_defaultSettings() { - let scopes = [ UberScope.allTrips, UberScope.history ] - let expectedHost = "https://auth.uber.com" - let expectedPath = "/oauth/v2/authorize" - let expectedScopes = scopes.toUberScopeString() - let expectedClientID = Configuration.shared.clientID - let expectedRedirect = Configuration.shared.getCallbackURI() - let expectedTokenType = "code" - let expectedState = "state123423" - - - let expectedQueryItems = [ - URLQueryItem(name: "scope", value: expectedScopes), - URLQueryItem(name: "client_id", value: expectedClientID), - URLQueryItem(name: "redirect_uri", value: expectedRedirect.absoluteString), - URLQueryItem(name: "signup_params", value: base64EncodedSignup), - URLQueryItem(name: "response_type", value: expectedTokenType), - URLQueryItem(name: "state", value: expectedState)] - - let login = OAuth.authorizationCodeLogin(clientID: expectedClientID, redirect: expectedRedirect, scopes: scopes, state: expectedState) - - XCTAssertEqual(login.host, expectedHost) - XCTAssertEqual(login.path, expectedPath) - XCTAssertEqual(login.query, expectedQueryItems) - } - - func testPar_forResponseTypeCode_defaultSettings() { - let expectedHost = "https://auth.uber.com" - let expectedPath = "/oauth/v2/par" - let expectedClientID = Configuration.shared.clientID - let expectedResponseType = OAuth.ResponseType.code - let expectedLoginHint: [String: String] = [ - "email": "test@test.com", - "phone": "5555555555", - "first_name": "First", - "last_name": "Last" - ] - let expectedLoginHintString = try! JSONSerialization.data(withJSONObject: expectedLoginHint).base64EncodedString() - - var components = URLComponents() - components.queryItems = [ - URLQueryItem(name: "client_id", value: expectedClientID), - URLQueryItem(name: "response_type", value: expectedResponseType.rawValue), - URLQueryItem(name: "login_hint", value: expectedLoginHintString), - ] - let expectedQueryItems = components.query! - - let login = OAuth.par(clientID: expectedClientID, loginHint: expectedLoginHint, responseType: expectedResponseType) - - let queryString = String(data: login.body!, encoding: .utf8) - - XCTAssertEqual(login.host, expectedHost) - XCTAssertEqual(login.path, expectedPath) - XCTAssertEqual(queryString, expectedQueryItems) - } - - func testPar_forResponseTypeToken_defaultSettings() { - let expectedHost = "https://auth.uber.com" - let expectedPath = "/oauth/v2/par" - let expectedClientID = Configuration.shared.clientID - let expectedResponseType = OAuth.ResponseType.token - let expectedLoginHint: [String: String] = [ - "email": "test@test.com", - "phone": "5555555555", - "first_name": "First", - "last_name": "Last" - ] - let expectedLoginHintString = try! JSONSerialization.data(withJSONObject: expectedLoginHint).base64EncodedString() - - var components = URLComponents() - components.queryItems = [ - URLQueryItem(name: "client_id", value: expectedClientID), - URLQueryItem(name: "response_type", value: expectedResponseType.rawValue), - URLQueryItem(name: "login_hint", value: expectedLoginHintString), - ] - let expectedQueryItems = components.query! - - let login = OAuth.par(clientID: expectedClientID, loginHint: expectedLoginHint, responseType: expectedResponseType) - - let queryString = String(data: login.body!, encoding: .utf8) - - XCTAssertEqual(login.host, expectedHost) - XCTAssertEqual(login.path, expectedPath) - XCTAssertEqual(queryString, expectedQueryItems) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/RefreshEndpointTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/RefreshEndpointTests.swift deleted file mode 100644 index 789ed55e..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/RefreshEndpointTests.swift +++ /dev/null @@ -1,133 +0,0 @@ -// -// RefreshEndpointTests.swift -// UberRides -// -// Copyright © 2016 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -import OHHTTPStubs -import OHHTTPStubsSwift -@testable import UberCore - -class RefreshEndpointTests: XCTestCase { - var session = URLSession.shared - var headers: [AnyHashable: Any]! - let timeout: Double = 1 - - let clientID = Configuration.shared.clientID - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - Configuration.shared.isSandbox = true - headers = ["Content-Type": "application/json"] - } - - override func tearDown() { - HTTPStubs.removeAllStubs() - Configuration.restoreDefaults() - super.tearDown() - } - - /** - Test 200 success response - */ - func test200Response() { - stub(condition: isHost("auth.uber.com")) { _ in - return HTTPStubsResponse(fileAtPath:OHPathForFile("refresh.json", type(of: self))!, statusCode:200, headers:self.headers) - } - let refreshToken = "ThisIsRefresh" - let expectation = self.expectation(description: "200 success response") - let endpoint = OAuth.refresh(clientID: clientID, refreshToken: refreshToken) - guard let request = Request(session: session, endpoint: endpoint) else { - XCTFail("unable to create request") - return - } - - request.execute({ response in - XCTAssertEqual(response.statusCode, 200) - XCTAssertNil(response.error) - - expectation.fulfill() - }) - - XCTAssertEqual(request.urlRequest.httpMethod, "POST") - - guard let bodyData = request.urlRequest.httpBody, let dataString = String(data: bodyData, encoding: String.Encoding.utf8) else { - XCTFail("Missing HTTP Body!") - return - } - var components = URLComponents() - components.query = dataString - - let expectedClientID = URLQueryItem(name: "client_id", value: clientID) - let expectedRefreshToken = URLQueryItem(name: "refresh_token", value: refreshToken) - - guard let queryItems = components.queryItems else { - XCTFail("Invalid HTTP Body!") - return - } - - XCTAssertTrue(queryItems.contains(expectedClientID)) - XCTAssertTrue(queryItems.contains(expectedRefreshToken)) - - waitForExpectations(timeout: timeout, handler: { error in - if let error = error { - print("Error: \(error.localizedDescription)") - } - request.cancelTasks() - }) - } - - /** - Test 400 authorization error response. - */ - func test400Error() { - let error = "invalid_refresh_token" - - stub(condition: isHost("auth.uber.com")) { _ in - let json = ["error": error] - return HTTPStubsResponse(jsonObject: json, statusCode: 400, headers: self.headers) - } - - let refreshToken = "ThisIsRefresh" - let expectation = self.expectation(description: "400 error response") - let endpoint = OAuth.refresh(clientID: clientID, refreshToken: refreshToken) - guard let request = Request(session: session, endpoint: endpoint) else { - XCTFail("unable to create request") - return - } - request.execute({ response in - XCTAssertEqual(response.statusCode, 400) - XCTAssertNotNil(response.error) - XCTAssertEqual(response.error?.title, error) - expectation.fulfill() - }) - - waitForExpectations(timeout: timeout, handler: { error in - if let error = error { - print("Error: \(error.localizedDescription)") - } - request.cancelTasks() - }) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/RidesAuthenticationDeeplinkTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/RidesAuthenticationDeeplinkTests.swift deleted file mode 100644 index 1bcc1f10..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/RidesAuthenticationDeeplinkTests.swift +++ /dev/null @@ -1,67 +0,0 @@ -// -// AuthenticationDeeplinkTests.swift -// UberRides -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest - -@testable import UberCore - -class RidesAuthenticationDeeplinkTests: XCTestCase { - - private var versionNumber: String? - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - versionNumber = Bundle(for: RidesAuthenticationDeeplink.self).object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String - } - - override func tearDown() { - Configuration.restoreDefaults() - super.tearDown() - } - - func testScheme() { - let authenticationDeeplink = RidesAuthenticationDeeplink(scopes:[]) - XCTAssertEqual(authenticationDeeplink.url.scheme, "uberauth") - } - - func testHost() { - let authenticationDeeplink = RidesAuthenticationDeeplink(scopes:[]) - XCTAssertEqual(authenticationDeeplink.url.host, "connect") - } - - func testPath() { - let authenticationDeeplink = RidesAuthenticationDeeplink(scopes:[]) - XCTAssertEqual(authenticationDeeplink.url.path, "") - } - - func testDeeplinkURL() { - let scopes = [UberScope.allTrips, UberScope.profile] - let authenticationDeeplink = RidesAuthenticationDeeplink(scopes:scopes) - let expectedURLPrefix = "uberauth://connect?" - - XCTAssertTrue(authenticationDeeplink.url.absoluteString.hasPrefix(expectedURLPrefix)) - } -} - - diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/TokenManagerTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/TokenManagerTests.swift deleted file mode 100644 index 7d0a0848..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/TokenManagerTests.swift +++ /dev/null @@ -1,223 +0,0 @@ -// -// TokenManagerTests.swift -// UberRides -// -// Copyright © 2015 Uber Technologies, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -@testable import UberCore - -class TokenManagerTests: XCTestCase { - - private var notificationFired = false - private var keychain: KeychainWrapper? - private var token: AccessToken! - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - keychain = KeychainWrapper() - notificationFired = false - token = AccessToken(tokenString: "testTokenString") - } - - override func tearDown() { - Configuration.restoreDefaults() - keychain = nil - super.tearDown() - } - - - func testSave() { - let identifier = "testIdentifier" - - XCTAssertTrue(TokenManager.save(accessToken: token!, tokenIdentifier:identifier)) - - guard let actualToken = keychain?.getObjectForKey(identifier) as? AccessToken else { - XCTFail("Unable to fetch token") - return - } - XCTAssertEqual(actualToken.tokenString, token?.tokenString) - - - XCTAssertTrue(keychain!.deleteObjectForKey(identifier)) - - } - - func testSave_firesNotification() { - let identifier = "testIdentifier" - - NotificationCenter.default.addObserver(self, selector: #selector(handleTokenManagerNotifications), name: NSNotification.Name(rawValue: TokenManager.tokenManagerDidSaveTokenNotification), object: nil) - - XCTAssertTrue(TokenManager.save(accessToken: token!, tokenIdentifier:identifier)) - - NotificationCenter.default.removeObserver(self) - - guard let actualToken = keychain?.getObjectForKey(identifier) as? AccessToken else { - XCTFail("Unable to fetch token") - return - } - XCTAssertEqual(actualToken.tokenString, token?.tokenString) - - XCTAssertTrue(notificationFired) - - XCTAssertTrue(keychain!.deleteObjectForKey(identifier)) - - } - - func testGet() { - - let identifier = "testIdentifier" - - XCTAssertTrue(keychain!.setObject(token!, key: identifier)) - - let actualToken = TokenManager.fetchToken(identifier: identifier) - XCTAssertNotNil(actualToken) - - XCTAssertEqual(actualToken?.tokenString, token?.tokenString) - - XCTAssertTrue(keychain!.deleteObjectForKey(identifier)) - } - - func testGet_nonExistent() { - let identifer = "there.is.no.token.named.this.123412wfdasd3o" - - XCTAssertNil(TokenManager.fetchToken(identifier: identifer)) - } - - func testDelete() { - let identifier = "testIdentifier" - - XCTAssertTrue(keychain!.setObject(token!, key: identifier)) - - XCTAssertTrue(TokenManager.deleteToken(identifier: identifier)) - - let actualToken = keychain?.getObjectForKey(identifier) as? AccessToken - guard actualToken == nil else { - XCTFail("Token should have been deleted") - XCTAssertTrue(keychain!.deleteObjectForKey(identifier)) - return - } - } - - func testDelete_nonExistent() { - let identifier = "there.is.no.token.named.this.123412wfdasd3o" - - XCTAssertFalse(TokenManager.deleteToken(identifier: identifier)) - - } - - func testDelete_firesNotification() { - - let identifier = "testIdentifier" - - XCTAssertTrue(keychain!.setObject(token!, key: identifier)) - - NotificationCenter.default.addObserver(self, selector: #selector(handleTokenManagerNotifications), name: NSNotification.Name(rawValue: TokenManager.tokenManagerDidDeleteTokenNotification), object: nil) - - XCTAssertTrue(TokenManager.deleteToken(identifier: identifier)) - - NotificationCenter.default.removeObserver(self) - - XCTAssertTrue(notificationFired) - - let actualToken = keychain?.getObjectForKey(identifier) as? AccessToken - guard actualToken == nil else { - XCTFail("Token should have been deleted") - XCTAssertTrue(keychain!.deleteObjectForKey(identifier)) - return - } - } - - func testDelete_nonExistent_doesNotFireNotification() { - let identifier = "there.is.no.token.named.this.123412wfdasd3o" - - NotificationCenter.default.addObserver(self, selector: #selector(handleTokenManagerNotifications), name: NSNotification.Name(rawValue: TokenManager.tokenManagerDidDeleteTokenNotification), object: nil) - - XCTAssertFalse(TokenManager.deleteToken(identifier: identifier)) - - NotificationCenter.default.removeObserver(self) - - XCTAssertFalse(notificationFired) - } - - func testCookiesCleared_whenTokenDeleted() { - guard let usUrl = URL(string: "https://login.uber.com") else { - XCTAssertFalse(false) - return - } - - let cookieStorage = HTTPCookieStorage.shared - - if let cookies = cookieStorage.cookies { - for cookie in cookies { - cookieStorage.deleteCookie(cookie) - } - } - - - cookieStorage.setCookies(createTestUSCookies(), for: usUrl, mainDocumentURL: nil) - UserDefaults.standard.synchronize() - XCTAssertEqual(cookieStorage.cookies?.count, 2) - XCTAssertEqual(cookieStorage.cookies(for: usUrl)?.count, 2) - - let identifier = "testIdentifier" - - _ = keychain?.setObject(token!, key: identifier) - - XCTAssertTrue(TokenManager.deleteToken(identifier: identifier)) - - let actualToken = keychain?.getObjectForKey(identifier) as? AccessToken - guard actualToken == nil else { - XCTAssert(false) - _ = keychain?.deleteObjectForKey(identifier) - return - } - - let testCookieStorage = HTTPCookieStorage.shared - XCTAssertEqual(testCookieStorage.cookies?.count, 0) - - } - - - //MARK: Helpers - - func createTestUSCookies() -> [HTTPCookie] { - let secureUSCookie = HTTPCookie(properties: [HTTPCookiePropertyKey.domain: ".uber.com", - HTTPCookiePropertyKey.path : "/", - HTTPCookiePropertyKey.name : "us_login_secure", - HTTPCookiePropertyKey.value : "some_value", - HTTPCookiePropertyKey.secure : true]) - let unsecureUSCookie = HTTPCookie(properties: [HTTPCookiePropertyKey.domain: ".uber.com", - HTTPCookiePropertyKey.path : "/", - HTTPCookiePropertyKey.name : "us_login_unecure", - HTTPCookiePropertyKey.value : "some_value", - HTTPCookiePropertyKey.secure : false]) - if let secureUSCookie = secureUSCookie, let unsecureUSCookie = unsecureUSCookie { - return [secureUSCookie, unsecureUSCookie] - } - return [] - } - - func handleTokenManagerNotifications() { - notificationFired = true - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/UberAppDelegateTests.swift b/examples/Swift SDK/Swift SDKTests/UberCore/UberAppDelegateTests.swift deleted file mode 100644 index dc0163f9..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/UberAppDelegateTests.swift +++ /dev/null @@ -1,146 +0,0 @@ -// -// RidesAppDelegateTests.swift -// UberRides -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -import XCTest -import CoreLocation -@testable import UberCore - -class UberAppDelegateTests : XCTestCase { - - private var versionNumber: String? - private var expectedDeeplinkUserAgent: String? - private var expectedButtonUserAgent: String? - - override func setUp() { - super.setUp() - Configuration.plistName = "testInfo" - Configuration.restoreDefaults() - Configuration.shared.clientID = "testClientID" - Configuration.shared.isSandbox = true - versionNumber = Bundle(for: UberAppDelegate.self).object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String - expectedDeeplinkUserAgent = "rides-ios-v\(versionNumber!)-deeplink" - expectedButtonUserAgent = "rides-ios-v\(versionNumber!)-button" - } - - override func tearDown() { - Configuration.restoreDefaults() - super.tearDown() - - } - - func testOpenUrlReturnsFalse_whenNoLoginManager() { - let appDelegate = UberAppDelegate.shared - - let testApp = UIApplication.shared - guard let url = URL(string: "http://www.google.com") else { - XCTFail() - return - } - - XCTAssertFalse(appDelegate.application(testApp, open: url, sourceApplication: nil, annotation: "")) - } - - func testOpenUrlReturnsTrue_callsOpenURLOnLoginManager() { - let expectation = self.expectation(description: "open URL called") - let appDelegate = UberAppDelegate.shared - let loginManagerMock = LoginManagingProtocolMock() - let testApp = UIApplication.shared - guard let testURL = URL(string: "http://www.google.com") else { - XCTFail() - return - } - let testSourceApplication = "testSource" - let testAnnotation = "annotation" - - let urlClosure: ((UIApplication, URL, String?, Any?) -> Bool) = { application, url, source, annotation in - XCTAssertEqual(application, testApp) - XCTAssertEqual(url, testURL) - XCTAssertEqual(source, testSourceApplication) - XCTAssertEqual(annotation as? String, testAnnotation) - expectation.fulfill() - return true - } - - loginManagerMock.openURLClosure = urlClosure - appDelegate.loginManager = loginManagerMock - XCTAssertTrue(appDelegate.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation)) - XCTAssertNil(appDelegate.loginManager) - waitForExpectations(timeout: 0.2, handler: nil) - } - - func testDidFinishLaunchingReturnsFalse_whenNoLaunchOptions() { - let appDelegate = UberAppDelegate.shared - let testApp = UIApplication.shared - XCTAssertFalse(appDelegate.application(testApp, didFinishLaunchingWithOptions: nil)) - } - - func testDidFinishLaunchingCallsOpenURL_whenLaunchURL() { - let expectation = self.expectation(description: "open URL called") - let appDelegate = UberAppDelegate.shared - let testApp = UIApplication.shared - let loginManagerMock = LoginManagingProtocolMock() - guard let testURL = URL(string: "http://www.google.com") else { - XCTFail() - return - } - let testSourceApplication = "testSource" - let testAnnotation = "annotation" - var launchOptions = [UIApplicationLaunchOptionsKey: Any]() - launchOptions[UIApplicationLaunchOptionsKey.url] = testURL as Any - launchOptions[UIApplicationLaunchOptionsKey.sourceApplication] = testSourceApplication as Any - launchOptions[UIApplicationLaunchOptionsKey.annotation] = testAnnotation as Any - - let urlClosure: ((UIApplication, URL, String?, Any?) -> Bool) = { application, url, source, annotation in - XCTAssertEqual(application, testApp) - XCTAssertEqual(url, testURL) - XCTAssertEqual(source, testSourceApplication) - XCTAssertEqual(annotation as? String, testAnnotation) - expectation.fulfill() - return true - } - - loginManagerMock.openURLClosure = urlClosure - appDelegate.loginManager = loginManagerMock - XCTAssertTrue(appDelegate.application(testApp, didFinishLaunchingWithOptions: launchOptions)) - XCTAssertNil(appDelegate.loginManager) - waitForExpectations(timeout: 0.2, handler: nil) - } - - func testDidBecomeActiveCallsLoginManager_whenDidBecomeActiveNotification() { - let expectation = self.expectation(description: "didBecomeActive called") - let appDelegate = UberAppDelegate.shared - let loginManagerMock = LoginManagingProtocolMock() - - let didBecomeActiveClosure: () -> () = { - expectation.fulfill() - } - - loginManagerMock.didBecomeActiveClosure = didBecomeActiveClosure - appDelegate.loginManager = loginManagerMock - - NotificationCenter.default.post(name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) - NotificationCenter.default.post(name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) - - waitForExpectations(timeout: 0.2) - } - -} diff --git a/examples/Swift SDK/Swift SDKTests/UberCore/UberMocks.swift b/examples/Swift SDK/Swift SDKTests/UberCore/UberMocks.swift deleted file mode 100644 index 4f86f335..00000000 --- a/examples/Swift SDK/Swift SDKTests/UberCore/UberMocks.swift +++ /dev/null @@ -1,122 +0,0 @@ -// -// UberMocks.swift -// UberCoreTests -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - - -@testable import UberCore -import UIKit - -class LoginManagerPartialMock: LoginManager { - var executeLoginClosure: ((AuthenticationCompletionHandler?) -> ())? - - public override func login(requestedScopes scopes: [UberScope], - presentingViewController: UIViewController?, - prefillValues: Prefill?, - completion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) { - executeLoginClosure?(completion) - } -} - -class LoginManagingProtocolMock: NSObject, LoginManaging { - - var loginClosure: (([UberScope], UIViewController?, ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) -> Void)? - var openURLClosure: ((UIApplication, URL, String?, Any?) -> Bool)? - var didBecomeActiveClosure: (() -> ())? - var willEnterForegroundClosure: (() -> ())? - - var backingManager: LoginManaging? - - init(loginManaging: LoginManaging? = nil) { - backingManager = loginManaging - super.init() - } - - func login(requestedScopes scopes: [UberScope], - presentingViewController: UIViewController?, - prefillValues: Prefill?, - completion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) { - if let closure = loginClosure { - closure(scopes, presentingViewController, completion) - } else if let manager = backingManager { - manager.login( - requestedScopes: scopes, - presentingViewController: presentingViewController, - prefillValues: nil, - completion: completion - ) - } - } - - func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any?) -> Bool { - if let closure = openURLClosure { - return closure(application, url, sourceApplication, annotation) - } else if let manager = backingManager { - return manager.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) - } else { - return false - } - } - - @available(iOS 9.0, *) - public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { - let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String - let annotation = options[.annotation] as Any? - - return application(app, open: url, sourceApplication: sourceApplication, annotation: annotation) - } - - func applicationDidBecomeActive() { - if let closure = didBecomeActiveClosure { - closure() - } else if let manager = backingManager { - manager.applicationDidBecomeActive() - } - } - - func applicationWillEnterForeground() { - if let closure = willEnterForegroundClosure { - closure() - } else { - backingManager?.applicationWillEnterForeground() - } - } -} - -class RidesNativeAuthenticatorPartialStub: BaseAuthenticator { - var consumeResponseCompletionValue: (AccessToken?, NSError?)? - override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) { - completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1) - } -} - -class EatsNativeAuthenticatorPartialStub: BaseAuthenticator { - var consumeResponseCompletionValue: (AccessToken?, NSError?)? - override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) { - completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1) - } -} - -class ImplicitAuthenticatorPartialStub: ImplicitGrantAuthenticator { - var consumeResponseCompletionValue: (AccessToken?, NSError?)? - override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) { - completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1) - } -} diff --git a/examples/Swift SDK/Swift SDKTests/UberRides/RequestButtonTests.swift b/examples/Swift SDK/Swift SDKTests/UberRides/RequestButtonTests.swift index 89e7a992..3cac7803 100644 --- a/examples/Swift SDK/Swift SDKTests/UberRides/RequestButtonTests.swift +++ b/examples/Swift SDK/Swift SDKTests/UberRides/RequestButtonTests.swift @@ -27,6 +27,7 @@ import OHHTTPStubs import OHHTTPStubsSwift import CoreLocation import WebKit +import UberAuth import UberCore @testable import UberRides @@ -37,6 +38,7 @@ class RequestButtonTests: XCTestCase { weak var errorExpectation: XCTestExpectation? var rideButtonError: UberError! let timeout: Double = 5 + private let tokenManager = TokenManager() override func setUp() { super.setUp() @@ -85,16 +87,21 @@ class RequestButtonTests: XCTestCase { let testIdentifier = "testAccessTokenIdentifier" let testToken = AccessToken(tokenString: "testTokenString") - _ = TokenManager.save(accessToken: testToken, tokenIdentifier: testIdentifier) + tokenManager.saveToken(testToken, identifier: testIdentifier) defer { - _ = TokenManager.deleteToken(identifier: testIdentifier) + tokenManager.deleteToken(identifier: testIdentifier) } let baseViewController = UIViewControllerMock() - let requestBehavior = RideRequestViewRequestingBehavior(presentingViewController: baseViewController) + let requestBehavior = RideRequestViewRequestingBehavior( + presentingViewController: baseViewController, + accessTokenIdentifier: testIdentifier + ) let button = RideRequestButton(rideParameters: RideParametersBuilder().build(), requestingBehavior: requestBehavior) - let loginManger = LoginManager(accessTokenIdentifier: testIdentifier) - let rideRequestVC = RideRequestViewController(rideParameters: RideParametersBuilder().build(), loginManager: loginManger) + let rideRequestVC = RideRequestViewController( + rideParameters: RideParametersBuilder().build(), + accessTokenIdentifier: testIdentifier + ) XCTAssertNotNil(rideRequestVC.view) let webViewMock = WebViewMock(frame: CGRect.zero, configuration: WKWebViewConfiguration(), testClosure: expectationClosure) diff --git a/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewControllerTests.swift b/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewControllerTests.swift index 05b93630..27307cb6 100644 --- a/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewControllerTests.swift +++ b/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewControllerTests.swift @@ -23,19 +23,22 @@ import XCTest import CoreLocation import WebKit +@testable import UberAuth @testable import UberCore @testable import UberRides class RideRequestViewControllerTests: XCTestCase { private let timeout: Double = 2 private let testIdentifier = "testAccessTokenIdentifier" - + private let tokenManager = TokenManager() + private var accessGroup: String { Configuration.shared.defaultKeychainAccessGroup } + override func setUp() { super.setUp() Configuration.plistName = "testInfo" Configuration.restoreDefaults() Configuration.shared.isSandbox = true - _ = TokenManager.deleteToken(identifier: testIdentifier) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) } override func tearDown() { @@ -43,38 +46,23 @@ class RideRequestViewControllerTests: XCTestCase { super.tearDown() } - func testAccessTokenMissing_whenNoAccessToken_loginFailed() { - var expectation = false - - let expectationClosure: (RideRequestViewController, NSError) -> () = {vc, error in - XCTAssertEqual(error.code, RideRequestViewErrorType.accessTokenMissing.rawValue) - XCTAssertEqual(error.domain, RideRequestViewErrorFactory.errorDomain) - expectation = true - } - let loginManager = LoginManager(loginType: .implicit) - let rideRequestVC = RideRequestViewController(rideParameters: RideParametersBuilder().build(), loginManager: loginManager) - let rideRequestVCDelegateMock = RideRequestViewControllerDelegateMock(testClosure: expectationClosure) - rideRequestVC.delegate = rideRequestVCDelegateMock - XCTAssertNotNil(rideRequestVC.view) - rideRequestVC.load() - loginManager.loginCompletion(accessToken: nil, error: UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unableToSaveAccessToken)) - - XCTAssertTrue(expectation) - } - func testRideRequestViewLoads_withValidAccessToken() { var expectation = false let expectationClosure: () -> () = { expectation = true } + let accessGroup = Configuration.shared.defaultKeychainAccessGroup let testToken = AccessToken(tokenString: "testTokenString") - _ = TokenManager.save(accessToken: testToken, tokenIdentifier: testIdentifier) + tokenManager.saveToken(testToken, identifier: testIdentifier, accessGroup: accessGroup) defer { - _ = TokenManager.deleteToken(identifier: testIdentifier) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) } - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .implicit) - let rideRequestVC = RideRequestViewController(rideParameters: RideParametersBuilder().build(), loginManager: loginManager) + let rideRequestVC = RideRequestViewController( + rideParameters: RideParametersBuilder().build(), + accessTokenIdentifier: testIdentifier, + keychainAccessGroup: accessGroup + ) rideRequestVC.rideRequestView = RideRequestViewMock(rideRequestView: rideRequestVC.rideRequestView, testClosure: expectationClosure) XCTAssertNotNil(rideRequestVC.view) rideRequestVC.load() @@ -84,31 +72,14 @@ class RideRequestViewControllerTests: XCTestCase { } func testLoginViewLoads_whenNoAccessToken() { - _ = TokenManager.deleteToken(identifier: testIdentifier) - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .native) - let rideRequestVC = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loginManager: loginManager) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) + let rideRequestVC = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build()) XCTAssertNotNil(rideRequestVC.view) rideRequestVC.load() - XCTAssert(loginManager.loggingIn) - } - - func testWidgetLoads_whenLoginSuccess() { - let testToken = AccessToken(tokenString: "test") - - _ = TokenManager.deleteToken(identifier: testIdentifier) - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .native) - let rideRequestVC = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loginManager: loginManager) - - XCTAssertNotNil(rideRequestVC.view) - - rideRequestVC.load() - loginManager.loginCompletion(accessToken: testToken, error: nil) - - XCTAssertFalse(rideRequestVC.rideRequestView.isHidden) - XCTAssertEqual(rideRequestVC.rideRequestView.accessToken, testToken) +// XCTAssert(loginManager.loggingIn) } func testRequestUsesCorrectSource_whenPresented() { @@ -135,12 +106,16 @@ class RideRequestViewControllerTests: XCTestCase { } let testToken = AccessToken(tokenString: "testTokenString") - _ = TokenManager.save(accessToken: testToken, tokenIdentifier: testIdentifier) + tokenManager.saveToken(testToken, identifier: testIdentifier, accessGroup: accessGroup) defer { - _ = TokenManager.deleteToken(identifier: testIdentifier) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) } - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .implicit) - let rideRequestVC = RideRequestViewController(rideParameters: RideParametersBuilder().build(), loginManager: loginManager) + let rideRequestVC = RideRequestViewController( + rideParameters: RideParametersBuilder().build(), + accessTokenIdentifier: testIdentifier, + keychainAccessGroup: accessGroup + ) + XCTAssertNotNil(rideRequestVC.view) let webViewMock = WebViewMock(frame: CGRect.zero, configuration: WKWebViewConfiguration(), testClosure: expectationClosure) @@ -159,13 +134,12 @@ class RideRequestViewControllerTests: XCTestCase { expectation = true } let testToken = AccessToken(tokenString: "testTokenString") - _ = TokenManager.save(accessToken: testToken, tokenIdentifier: testIdentifier) + tokenManager.saveToken(testToken, identifier: testIdentifier, accessGroup: accessGroup) defer { - _ = TokenManager.deleteToken(identifier: testIdentifier) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) } - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .implicit) - let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loginManager: loginManager, loadClosure: nil, networkClosure: networkClosure, presentViewControllerClosure: nil) + let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loadClosure: nil, networkClosure: networkClosure, presentViewControllerClosure: nil) (rideRequestViewControllerMock as RideRequestViewDelegate).rideRequestView(rideRequestViewControllerMock.rideRequestView, didReceiveError: RideRequestViewErrorFactory.errorForType(.networkError)) @@ -178,11 +152,9 @@ class RideRequestViewControllerTests: XCTestCase { let networkClosure: () -> () = { expectation = true } - _ = TokenManager.deleteToken(identifier: testIdentifier) - - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .implicit) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) - let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loginManager: loginManager, loadClosure: nil, networkClosure: networkClosure, presentViewControllerClosure: nil) + let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loadClosure: nil, networkClosure: networkClosure, presentViewControllerClosure: nil) (rideRequestViewControllerMock as RideRequestViewDelegate).rideRequestView(rideRequestViewControllerMock.rideRequestView, didReceiveError: RideRequestViewErrorFactory.errorForType(.networkError)) @@ -198,13 +170,12 @@ class RideRequestViewControllerTests: XCTestCase { XCTAssertTrue(type(of: viewController) == UIAlertController.self) } let testToken = AccessToken(tokenString: "testTokenString") - _ = TokenManager.save(accessToken: testToken, tokenIdentifier: testIdentifier) + tokenManager.saveToken(testToken, identifier: testIdentifier, accessGroup: accessGroup) defer { - _ = TokenManager.deleteToken(identifier: testIdentifier) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) } - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .implicit) - let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loginManager: loginManager, loadClosure: nil, networkClosure: nil, presentViewControllerClosure: presentViewControllerClosure) + let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loadClosure: nil, networkClosure: nil, presentViewControllerClosure: presentViewControllerClosure) let requestViewMock = RideRequestViewMock(rideRequestView: rideRequestViewControllerMock.rideRequestView) { () -> () in requestViewExpectation = true @@ -224,11 +195,9 @@ class RideRequestViewControllerTests: XCTestCase { let notSupportedClosure: () -> () = { expectation = true } - _ = TokenManager.deleteToken(identifier: testIdentifier) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .implicit) - - let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loginManager: loginManager, notSupportedClosure: notSupportedClosure) + let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), notSupportedClosure: notSupportedClosure) (rideRequestViewControllerMock as RideRequestViewDelegate).rideRequestView(rideRequestViewControllerMock.rideRequestView, didReceiveError: RideRequestViewErrorFactory.errorForType(.notSupported)) @@ -243,11 +212,9 @@ class RideRequestViewControllerTests: XCTestCase { XCTAssertTrue(type(of: viewController) == UIAlertController.self) } - _ = TokenManager.deleteToken(identifier: testIdentifier) - - let loginManager = LoginManager(accessTokenIdentifier: testIdentifier, keychainAccessGroup: Configuration.shared.defaultKeychainAccessGroup, loginType: .implicit) + tokenManager.deleteToken(identifier: testIdentifier, accessGroup: accessGroup) - let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), loginManager: loginManager, presentViewControllerClosure: presentViewControllerClosure) + let rideRequestViewControllerMock = RideRequestViewControllerMock(rideParameters: RideParametersBuilder().build(), presentViewControllerClosure: presentViewControllerClosure) (rideRequestViewControllerMock as RideRequestViewDelegate).rideRequestView(rideRequestViewControllerMock.rideRequestView, didReceiveError: RideRequestViewErrorFactory.errorForType(.notSupported)) diff --git a/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewRequestingBehaviorTests.swift b/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewRequestingBehaviorTests.swift index e1bed623..e9c00e71 100644 --- a/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewRequestingBehaviorTests.swift +++ b/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewRequestingBehaviorTests.swift @@ -22,7 +22,8 @@ import XCTest import CoreLocation -import UberCore +@testable import UberAuth +@testable import UberCore @testable import UberRides class RideRequestViewRequestingBehaviorTests : XCTestCase { @@ -39,19 +40,6 @@ class RideRequestViewRequestingBehaviorTests : XCTestCase { Configuration.restoreDefaults() } - func testUpdateLoginManager() { - let baseVC = UIViewController() - let initialLoginManger = LoginManager(loginType: .native) - let behavior = RideRequestViewRequestingBehavior(presentingViewController: baseVC, loginManager: initialLoginManger) - XCTAssertNotNil(behavior.loginManager) - XCTAssertEqual(behavior.modalRideRequestViewController.rideRequestViewController.loginManager, initialLoginManger) - - let newLoginManager = LoginManager(accessTokenIdentifier: "testToken") - behavior.loginManager = newLoginManager - XCTAssertNotNil(behavior.loginManager) - XCTAssertEqual(behavior.modalRideRequestViewController.rideRequestViewController.loginManager, newLoginManager) - } - func testRideParametersUpdated() { class UIViewControllerMock : UIViewController { override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) { @@ -60,8 +48,7 @@ class RideRequestViewRequestingBehaviorTests : XCTestCase { } let baseVC = UIViewControllerMock() - let initialLoginManger = LoginManager(loginType: .native) - let behavior = RideRequestViewRequestingBehavior(presentingViewController: baseVC, loginManager: initialLoginManger) + let behavior = RideRequestViewRequestingBehavior(presentingViewController: baseVC) XCTAssertNotNil(behavior.modalRideRequestViewController) XCTAssertNotNil(behavior.modalRideRequestViewController.rideRequestViewController) let pickupLocation = CLLocation(latitude: -32.0, longitude: 42.2) @@ -97,8 +84,7 @@ class RideRequestViewRequestingBehaviorTests : XCTestCase { } let baseVC = UIViewControllerMock(testClosure: expectationClosure) - let initialLoginManger = LoginManager(loginType: .native) - let behavior = RideRequestViewRequestingBehavior(presentingViewController: baseVC, loginManager: initialLoginManger) + let behavior = RideRequestViewRequestingBehavior(presentingViewController: baseVC) behavior.requestRide(parameters: RideParametersBuilder().build()) waitForExpectations(timeout: 2.0) {error in XCTAssertNil(error) diff --git a/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewTests.swift b/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewTests.swift index 3543a404..9f0a1624 100644 --- a/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewTests.swift +++ b/examples/Swift SDK/Swift SDKTests/UberRides/RideRequestViewTests.swift @@ -24,13 +24,15 @@ import XCTest import WebKit -import UberCore +@testable import UberAuth +@testable import UberCore @testable import UberRides class RideRequestViewTests: XCTestCase { var testExpectation: XCTestExpectation! var error: NSError? let timeout: TimeInterval = 10 + private let tokenManager = TokenManager() override func setUp() { super.setUp() @@ -49,7 +51,11 @@ class RideRequestViewTests: XCTestCase { */ func testAccessTokenExpired() { testExpectation = expectation(description: "access token expired delegate call") - let view = RideRequestView(rideParameters: RideParametersBuilder().build()) + let view = RideRequestView( + rideParameters: RideParametersBuilder().build(), + accessTokenIdentifier: Configuration.shared.defaultAccessTokenIdentifier, + accessGroup: Configuration.shared.defaultKeychainAccessGroup + ) view.delegate = self let request = URLRequest(url: URL(string: "uberConnect://oauth#error=unauthorized")!) view.webView.load(request) @@ -92,13 +98,13 @@ class RideRequestViewTests: XCTestCase { */ func testAuthorizeWithTokenManagerAccessToken() { let token = AccessToken(tokenString: "accessToken1234") - _ = TokenManager.save(accessToken: token) + _ = tokenManager.saveToken(token) let view = RideRequestView() XCTAssertNotNil(view.accessToken) - XCTAssertEqual(view.accessToken?.tokenString, TokenManager.fetchToken()?.tokenString) + XCTAssertEqual(view.accessToken?.tokenString, tokenManager.getToken()?.tokenString) - _ = TokenManager.deleteToken() + _ = tokenManager.deleteToken() } /** @@ -118,7 +124,7 @@ class RideRequestViewTests: XCTestCase { testExpectation = expectation(description: "access token missing delegate call") let view = RideRequestView() view.delegate = self - _ = TokenManager.deleteToken() + _ = tokenManager.deleteToken() view.load() @@ -153,14 +159,14 @@ class RideRequestViewTests: XCTestCase { } let testIdentifier = "testAccessTokenIdentifier" - _ = TokenManager.deleteToken(identifier: testIdentifier) + _ = tokenManager.deleteToken(identifier: testIdentifier) let testToken = AccessToken(tokenString: "testTokenString") - _ = TokenManager.save(accessToken: testToken, tokenIdentifier: testIdentifier) + _ = tokenManager.saveToken(testToken, identifier: testIdentifier) defer { - _ = TokenManager.deleteToken(identifier: testIdentifier) + _ = tokenManager.deleteToken(identifier: testIdentifier) } - let rideRequestView = RideRequestView(rideParameters: RideParametersBuilder().build(), accessToken: TokenManager.fetchToken(identifier: testIdentifier), frame: CGRect.zero) + let rideRequestView = RideRequestView(rideParameters: RideParametersBuilder().build(), accessToken: tokenManager.getToken(identifier: testIdentifier), frame: CGRect.zero) XCTAssertNotNil(rideRequestView) let webViewMock = WebViewMock(frame: CGRect.zero, configuration: WKWebViewConfiguration(), testClosure: expectationClosure) diff --git a/examples/Swift SDK/Swift SDKTests/UberRides/RidesClientTests.swift b/examples/Swift SDK/Swift SDKTests/UberRides/RidesClientTests.swift index 84b804fd..193696c0 100644 --- a/examples/Swift SDK/Swift SDKTests/UberRides/RidesClientTests.swift +++ b/examples/Swift SDK/Swift SDKTests/UberRides/RidesClientTests.swift @@ -26,6 +26,7 @@ import XCTest import OHHTTPStubs import OHHTTPStubsSwift import CoreLocation +@testable import UberAuth @testable import UberCore @testable import UberRides @@ -843,60 +844,11 @@ class RidesClientTests: XCTestCase { } func testRefreshToken() { - stub(condition: isHost("auth.uber.com")) { _ in - return HTTPStubsResponse(fileAtPath: OHPathForFile("refresh.json", type(of: self))!, statusCode: 200, headers: nil) - } - let refreshToken = "thisIsRefresh" - let expectedScopeString = "request all_trips profile ride_widgets history places history_lite" - let expectedScopes = expectedScopeString.toUberScopesArray() - let expectedScopeSet = Set(expectedScopes) - - let expectation = self.expectation(description: "Refresh token completion") - client.refreshAccessToken(usingRefreshToken: refreshToken, completion: { accessToken, response in - guard let accessToken = accessToken else { - XCTAssert(false) - return - } - let scopes = accessToken.grantedScopes - - XCTAssertEqual(accessToken.tokenString, "Access999Token") - XCTAssertEqual(accessToken.refreshToken, "888RefreshToken") - - let testScopeSet = Set(scopes) - XCTAssertEqual(testScopeSet, expectedScopeSet) - - XCTAssertEqual(response.statusCode, 200) - expectation.fulfill() - }) - - waitForExpectations(timeout: timeout, handler: { error in - XCTAssertNil(error) - }) + // TODO: Will update after refresh token implementation } func testRefreshTokenInvalid() { - stub(condition: isHost("auth.uber.com")) { _ in - return HTTPStubsResponse(jsonObject: ["error":"invalid_refresh_token"], statusCode: 400, headers: nil) - } - let refreshToken = "thisIsRefresh" - - let expectation = self.expectation(description: "Refresh token completion") - client.refreshAccessToken(usingRefreshToken: refreshToken, completion: { accessToken, response in - XCTAssertNil(accessToken) - - guard let error = response.error else { - XCTFail() - return - } - XCTAssertEqual(error.title, "invalid_refresh_token") - - XCTAssertEqual(response.statusCode, 400) - expectation.fulfill() - }) - - waitForExpectations(timeout: timeout, handler: { error in - XCTAssertNil(error) - }) + // TODO: Will update after refresh token implementation } func testTokenType() { @@ -912,15 +864,14 @@ class RidesClientTests: XCTestCase { func testGetAccessTokenSuccess_defaultId_defaultGroup() { let token = AccessToken(tokenString: "testAccessToken") - let keychainHelper = KeychainWrapper() + let keychainHelper = KeychainUtility() let tokenKey = Configuration.shared.defaultAccessTokenIdentifier let tokenGroup = Configuration.shared.defaultKeychainAccessGroup - keychainHelper.setAccessGroup(tokenGroup) - XCTAssertTrue(keychainHelper.setObject(token, key: tokenKey)) + XCTAssertTrue(keychainHelper.save(token, for: tokenKey, accessGroup: tokenGroup)) defer { - XCTAssertTrue(keychainHelper.deleteObjectForKey(tokenKey)) + XCTAssertTrue(keychainHelper.delete(key: tokenKey, accessGroup: tokenGroup)) } let ridesClient = RidesClient() @@ -947,15 +898,14 @@ class RidesClientTests: XCTestCase { */ func testGetAccessTokenSuccess_customId_defaultGroup() { let token = AccessToken(tokenString: "testAccessToken") - let keychainHelper = KeychainWrapper() + let keychainHelper = KeychainUtility() let tokenKey = "newTokenKey" let tokenGroup = Configuration.shared.defaultKeychainAccessGroup - keychainHelper.setAccessGroup(tokenGroup) - XCTAssertTrue(keychainHelper.setObject(token, key: tokenKey)) + XCTAssertTrue(keychainHelper.save(token, for: tokenKey, accessGroup: tokenGroup)) defer { - XCTAssertTrue(keychainHelper.deleteObjectForKey(tokenKey)) + XCTAssertTrue(keychainHelper.delete(key: tokenKey, accessGroup: tokenGroup)) } let ridesClient = RidesClient(accessTokenIdentifier: tokenKey) diff --git a/examples/Swift SDK/Swift SDKTests/UberRides/RidesMocks.swift b/examples/Swift SDK/Swift SDKTests/UberRides/RidesMocks.swift index adc01f74..d3b0a261 100644 --- a/examples/Swift SDK/Swift SDKTests/UberRides/RidesMocks.swift +++ b/examples/Swift SDK/Swift SDKTests/UberRides/RidesMocks.swift @@ -21,6 +21,7 @@ // THE SOFTWARE. import WebKit +@testable import UberAuth @testable import UberCore @testable import UberRides @@ -54,12 +55,16 @@ class RideRequestViewControllerMock : RideRequestViewController { var notSupportedClosure: (() -> ())? var presentViewControllerClosure: ((UIViewController, Bool, (() -> Void)?) -> ())? - init(rideParameters: RideParameters, loginManager: LoginManager, loadClosure: (() -> ())? = nil, networkClosure: (() -> ())? = nil, presentViewControllerClosure: ((UIViewController, Bool, (() -> Void)?) -> ())? = nil, notSupportedClosure: (() -> ())? = nil) { + init(rideParameters: RideParameters, loadClosure: (() -> ())? = nil, networkClosure: (() -> ())? = nil, presentViewControllerClosure: ((UIViewController, Bool, (() -> Void)?) -> ())? = nil, notSupportedClosure: (() -> ())? = nil, accessTokenIdentifier: String = Configuration.shared.defaultAccessTokenIdentifier, keychainAccessGroup: String = Configuration.shared.defaultKeychainAccessGroup) { self.loadClosure = loadClosure self.networkClosure = networkClosure self.notSupportedClosure = notSupportedClosure self.presentViewControllerClosure = presentViewControllerClosure - super.init(rideParameters: rideParameters, loginManager: loginManager) + super.init( + rideParameters: rideParameters, + accessTokenIdentifier: accessTokenIdentifier, + keychainAccessGroup: keychainAccessGroup + ) } required init?(coder aDecoder: NSCoder) {