From 1fde7a3a947501ae89c0433aef8801b1ef4d9575 Mon Sep 17 00:00:00 2001 From: Sandro Machado Date: Fri, 15 Sep 2017 18:22:21 +0100 Subject: [PATCH 1/2] Update to Swift 3 --- .gitignore | 4 + .swiftlint.yml | 2 + .travis.yml | 11 +- Cartfile | 10 +- Cartfile.private | 4 +- Cartfile.resolved | 14 +- README.md | 11 +- SampleApplication.xcodeproj/project.pbxproj | 39 ++- .../xcschemes/SampleApplication.xcscheme | 2 +- SampleApplication/AppDelegate.swift | 8 +- .../LoginViewController.swift | 34 +-- .../UserViewController.swift | 18 +- .../Client/AuthorizationViewController.swift | 6 +- Source/Client/SessionManager.swift | 10 +- Source/Client/UpholdClient.swift | 40 +-- Source/Client/UpholdClientErrorHandling.swift | 18 +- Source/Client/UpholdRestAdapter.swift | 46 +-- .../Configurations/GlobalConfigurations.swift | 12 +- .../ErrorHandling/ApiLimitExceedError.swift | 2 +- .../ErrorHandling/AuthenticationError.swift | 2 +- .../AuthenticationRequiredError.swift | 2 +- Source/ErrorHandling/BadRequestError.swift | 2 +- .../ConfigurationMissingError.swift | 2 +- Source/ErrorHandling/LogicError.swift | 2 +- Source/ErrorHandling/MalformedUrlError.swift | 2 +- Source/ErrorHandling/NotFoundError.swift | 2 +- Source/ErrorHandling/StateMatchError.swift | 2 +- .../UnexpectedResponseError.swift | 2 +- Source/ErrorHandling/UnhandledError.swift | 2 +- Source/ErrorHandling/UpholdClientError.swift | 2 +- Source/Model/Account.swift | 6 +- Source/Model/AuthenticationRequest.swift | 6 +- Source/Model/AuthenticationResponse.swift | 6 +- Source/Model/Balance.swift | 6 +- Source/Model/Balance/Currency.swift | 6 +- Source/Model/Balance/UserBalance.swift | 6 +- Source/Model/BaseModel.swift | 2 +- Source/Model/Card.swift | 50 ++-- Source/Model/Card/Address.swift | 6 +- Source/Model/Card/AddressRequest.swift | 6 +- Source/Model/Card/CardRequest.swift | 6 +- Source/Model/Card/CardSettings.swift | 6 +- Source/Model/Card/NormalizedCard.swift | 6 +- Source/Model/Document.swift | 2 +- Source/Model/Rate.swift | 6 +- Source/Model/Reserve.swift | 50 ++-- Source/Model/Reserve/Deposit.swift | 6 +- Source/Model/Reserve/DepositMovement.swift | 6 +- Source/Model/Reserve/ReserveStatistics.swift | 6 +- Source/Model/Reserve/Total.swift | 6 +- Source/Model/Reserve/Value.swift | 6 +- Source/Model/Token.swift | 6 +- Source/Model/Transaction.swift | 40 +-- Source/Model/Transaction/Denomination.swift | 6 +- Source/Model/Transaction/Destination.swift | 6 +- Source/Model/Transaction/Fee.swift | 6 +- Source/Model/Transaction/Merchant.swift | 2 +- .../Transaction/NormalizedTransaction.swift | 6 +- Source/Model/Transaction/Origin.swift | 6 +- Source/Model/Transaction/Parameters.swift | 6 +- Source/Model/Transaction/Source.swift | 6 +- .../TransactionCardDepositRequest.swift | 10 +- .../TransactionCommitRequest.swift | 6 +- .../TransactionDenominationRequest.swift | 6 +- .../TransactionDepositRequest.swift | 10 +- .../Transaction/TransactionRequest.swift | 6 +- .../TransactionTransferRequest.swift | 10 +- Source/Model/User.swift | 114 +++---- Source/Model/User/Contact.swift | 6 +- Source/Model/User/ContactRequest.swift | 6 +- .../InternationalizationUserSetting.swift | 6 +- .../InternationalizationUserSettings.swift | 6 +- Source/Model/User/Phone.swift | 6 +- Source/Model/User/Settings/Otp.swift | 6 +- Source/Model/User/Settings/Otp/Login.swift | 6 +- .../User/Settings/Otp/Transactions.swift | 6 +- .../User/Settings/Otp/Transactions/Send.swift | 6 +- .../Settings/Otp/Transactions/Transfer.swift | 6 +- .../Settings/Otp/Transactions/Withdraw.swift | 6 +- .../Otp/Transactions/Withdraw/Crypto.swift | 6 +- Source/Model/User/UserSettings.swift | 10 +- Source/Paginator/Paginator.swift | 20 +- Source/Paginator/PaginatorProtocol.swift | 6 +- Source/Service/AccountsService.swift | 6 +- Source/Service/OAuth2Service.swift | 4 +- Source/Service/ReserveService.swift | 10 +- Source/Service/TickerService.swift | 6 +- Source/Service/UserCardService.swift | 38 +-- Source/Service/UserService.swift | 24 +- Source/Util/Header.swift | 14 +- Source/Util/ResourcesUtil.swift | 22 +- Source/Util/URLUtils.swift | 8 +- .../Integration/Paginator/PaginatorTest.swift | 78 ----- .../ClientTests}/SessionManagerTest.swift | 22 +- .../ClientTests}/UpholdClientTest.swift | 76 +++-- .../ClientTests}/UpholdRestAdapterTest.swift | 228 +++++++------- .../UpholdClientErrorHandlingTest.swift | 30 +- .../ModelTests}/CardTest.swift | 223 ++++++++------ .../ModelTests}/RateTest.swift | 4 +- .../ModelTests}/ReserveTest.swift | 102 ++++--- .../ModelTests}/TransactionTest.swift | 210 +++++++------ .../ModelTests}/UserTest.swift | 279 +++++++++++------- .../PaginatorTests/PaginatorTest.swift | 86 ++++++ .../ServiceTests}/AccountsServiceTest.swift | 2 +- .../ServiceTests}/OAuth2ServiceTest.swift | 6 +- .../ServiceTests}/ReserveServiceTest.swift | 6 +- .../ServiceTests}/TickerServiceTest.swift | 2 +- .../ServiceTests}/UserCardServiceTest.swift | 20 +- .../ServiceTests}/UserServiceTest.swift | 8 +- .../UtilTests/HeaderTest.swift | 36 +++ .../UtilTests}/ResourcesUtilTest.swift | 6 +- .../UtilTests}/URLUtilsTest.swift | 2 +- .../GlobalConfigurationProductionTest.swift | 0 .../GlobalConfigurationSandboxTest.swift | 0 Tests/{Util => UtilTests}/Fixtures.swift | 26 +- Tests/{Util => UtilTests}/JSONTestUtils.swift | 4 +- Tests/UtilTests/MockBaseModel.swift | 17 ++ Tests/UtilTests/MockKeychain.swift | 32 ++ Tests/{Util => UtilTests}/MockRequest.swift | 27 +- .../{Util => UtilTests}/MockRestAdapter.swift | 12 +- Tests/UtilTests/MockSessionManager.swift | 64 ++++ Tests/UtilTests/MockToken.swift | 42 +++ Tests/UtilTests/MockUpholdClient.swift | 54 ++++ .../{Util => UtilTests}/UpholdTestCase.swift | 4 +- UpholdSdk.podspec.json | 10 +- UpholdSdk.xcodeproj/project.pbxproj | 183 +++++++++--- .../xcshareddata/xcschemes/UpholdSdk.xcscheme | 2 +- .../xcschemes/UpholdSdkSandbox.xcscheme | 2 +- 128 files changed, 1756 insertions(+), 1160 deletions(-) delete mode 100644 Tests/Integration/Paginator/PaginatorTest.swift rename Tests/{Integration/Client => IntegrationTests/ClientTests}/SessionManagerTest.swift (56%) rename Tests/{Integration/Client => IntegrationTests/ClientTests}/UpholdClientTest.swift (80%) rename Tests/{Integration/Client => IntegrationTests/ClientTests}/UpholdRestAdapterTest.swift (59%) rename Tests/{Integration/ErrorHandling => IntegrationTests/ErrorHandlingTests}/UpholdClientErrorHandlingTest.swift (83%) rename Tests/{Integration/Model => IntegrationTests/ModelTests}/CardTest.swift (76%) rename Tests/{Integration/Model => IntegrationTests/ModelTests}/RateTest.swift (74%) rename Tests/{Integration/Model => IntegrationTests/ModelTests}/ReserveTest.swift (73%) rename Tests/{Integration/Model => IntegrationTests/ModelTests}/TransactionTest.swift (74%) rename Tests/{Integration/Model => IntegrationTests/ModelTests}/UserTest.swift (73%) create mode 100644 Tests/IntegrationTests/PaginatorTests/PaginatorTest.swift rename Tests/{Integration/Service => IntegrationTests/ServiceTests}/AccountsServiceTest.swift (90%) rename Tests/{Integration/Service => IntegrationTests/ServiceTests}/OAuth2ServiceTest.swift (70%) rename Tests/{Integration/Service => IntegrationTests/ServiceTests}/ReserveServiceTest.swift (88%) rename Tests/{Integration/Service => IntegrationTests/ServiceTests}/TickerServiceTest.swift (90%) rename Tests/{Integration/Service => IntegrationTests/ServiceTests}/UserCardServiceTest.swift (81%) rename Tests/{Integration/Service => IntegrationTests/ServiceTests}/UserServiceTest.swift (91%) create mode 100644 Tests/IntegrationTests/UtilTests/HeaderTest.swift rename Tests/{Integration/Util => IntegrationTests/UtilTests}/ResourcesUtilTest.swift (61%) rename Tests/{Integration/Util => IntegrationTests/UtilTests}/URLUtilsTest.swift (79%) rename Tests/{Unit => UnitTests}/GlobalConfigurationProductionTest.swift (100%) rename Tests/{Unit => UnitTests}/GlobalConfigurationSandboxTest.swift (100%) rename Tests/{Util => UtilTests}/Fixtures.swift (94%) rename Tests/{Util => UtilTests}/JSONTestUtils.swift (78%) create mode 100644 Tests/UtilTests/MockBaseModel.swift create mode 100644 Tests/UtilTests/MockKeychain.swift rename Tests/{Util => UtilTests}/MockRequest.swift (50%) rename Tests/{Util => UtilTests}/MockRestAdapter.swift (77%) create mode 100644 Tests/UtilTests/MockSessionManager.swift create mode 100644 Tests/UtilTests/MockToken.swift create mode 100644 Tests/UtilTests/MockUpholdClient.swift rename Tests/{Util => UtilTests}/UpholdTestCase.swift (74%) diff --git a/.gitignore b/.gitignore index 24c61f5..104f2ff 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,10 @@ Carthage/ # Mac OS X .DS_Store +# Swift package manager +.build/ +Packages/ + # Xcode settings !default.mode1v3 !default.mode2v3 diff --git a/.swiftlint.yml b/.swiftlint.yml index b1c39b6..656518b 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -1,8 +1,10 @@ disabled_rules: + - conditional_binding_cascade - control_statement - file_length - function_body_length - function_parameter_count + - implicit_getter - line_length - type_body_length - variable_name diff --git a/.travis.yml b/.travis.yml index e8a4edf..95a6743 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,16 +1,17 @@ language: objective-c -osx_image: xcode7.3 +osx_image: xcode8.3 env: - SCHEME=UpholdSdk - SCHEME=UpholdSdkSandbox before_script: - - carthage update --platform iOS - # Workaround introduced to fix the xctool issue #454 (https://github.com/facebook/xctool/issues/454). - - open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app --args -CurrentDeviceUDID 75FC400A-B2AA-4DD6-B159-8687FAA5018A + - carthage bootstrap --platform iOS --no-build + - cd Carthage/Checkouts/URITemplate.swift && echo "IPHONEOS_DEPLOYMENT_TARGET = 8.0" > Configuration.xcconfig && swift package generate-xcodeproj --xcconfig-overrides Configuration.xcconfig + - cd ../../../ + - carthage build --platform iOS --configuration ProductionRelease script: - swiftlint lint --strict - - xctool -project UpholdSdk.xcodeproj -scheme $SCHEME test sdk iphonesimulator CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + - xcodebuild -project UpholdSdk.xcodeproj test -scheme $SCHEME -sdk iphonesimulator -destination "name=iPhone SE" | xcpretty diff --git a/Cartfile b/Cartfile index 939a967..d027cc2 100644 --- a/Cartfile +++ b/Cartfile @@ -1,5 +1,5 @@ -github "Hearst-DD/ObjectMapper" ~> 1.2.0 -github "mxcl/OMGHTTPURLRQ" ~> 3.1.2 -github "mxcl/PromiseKit" ~> 3.2.1 -github "marketplacer/keychain-swift" ~> 3.0.13 -github "theadam/SwiftClient" ~> 2.0.3 +github "Hearst-DD/ObjectMapper" ~> 2.2.8 +github "mxcl/OMGHTTPURLRQ" ~> 3.2.2 +github "mxcl/PromiseKit" ~> 4.1.8 +github "marketplacer/keychain-swift" ~> 7.0.1 +github "theadam/SwiftClient" ~> 3.0.3 diff --git a/Cartfile.private b/Cartfile.private index b433850..5223b6c 100644 --- a/Cartfile.private +++ b/Cartfile.private @@ -1,2 +1,2 @@ -github "vadymmarkov/Fakery" ~> 1.2.0 -github "seegno-forks/Mockingjay" "support/add-carthage-configuration" +github "vadymmarkov/Fakery" ~> 2.0.0 +github "uphold-forks/Mockingjay" "support/add-carthage-configuration" diff --git a/Cartfile.resolved b/Cartfile.resolved index 950428d..34bc2a6 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,8 +1,8 @@ -github "vadymmarkov/Fakery" "1.4.0" +github "vadymmarkov/Fakery" "2.0.0" github "mxcl/OMGHTTPURLRQ" "3.2.2" -github "Hearst-DD/ObjectMapper" "1.5.0" -github "mxcl/PromiseKit" "3.5.3" -github "theadam/SwiftClient" "2.0.3" -github "kylef/URITemplate.swift" "175429f708de77e1c894e2fa4bc6c61f461822bb" -github "marketplacer/keychain-swift" "3.0.16" -github "seegno-forks/Mockingjay" "68b619819ecee654297ff2349b934032c33581f9" +github "Hearst-DD/ObjectMapper" "2.2.8" +github "mxcl/PromiseKit" "4.4.1" +github "theadam/SwiftClient" "3.0.3" +github "kylef/URITemplate.swift" "2.0.1" +github "marketplacer/keychain-swift" "7.0.1" +github "uphold-forks/Mockingjay" "40275c6b531fb9514327d9ce09e0acf9128a774c" diff --git a/README.md b/README.md index 1eebb6b..4cbb226 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ The Uphold SDK for iOS provides an easy way for developers to integrate iOS appl ## Requirements - * Xcode 7 - * Swift 2 + * Xcode 8 + * Swift 3 * Carthage or CocoaPods ## Installation @@ -17,7 +17,7 @@ The Uphold SDK for iOS provides an easy way for developers to integrate iOS appl 1. Add to your `Podfile`. ``` - platform :ios, '9.0' + platform :ios, '10.0' use_frameworks! # To use Uphold's production environment. @@ -117,6 +117,8 @@ upholdClient.getUser().then { (user: User) -> () in } ``` +Note: Don't forget to add keychain sharing capabilities in your application's target inside the `Capabilities` tab. + ### Get user cards with chaining ```swift @@ -337,7 +339,8 @@ To build the sample application you need the [Xcode](https://developer.apple.com ``` 3. Open the sample project `SampleApplication.xcodeproj`. -4. Build and run the app from inside Xcode. +4. Add keychain sharing capabilities. +5. Build and run the app from inside Xcode. The sample application is configured to use the [sandbox environment](https://sandbox.uphold.com), make sure you use a sandbox account to perform the login. diff --git a/SampleApplication.xcodeproj/project.pbxproj b/SampleApplication.xcodeproj/project.pbxproj index 58b408e..eb5ea90 100644 --- a/SampleApplication.xcodeproj/project.pbxproj +++ b/SampleApplication.xcodeproj/project.pbxproj @@ -184,11 +184,18 @@ BC2381051BB461DE0060CC80 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0700; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = Uphold; TargetAttributes = { BC23810C1BB461DE0060CC80 = { CreatedOnToolsVersion = 7.0; + DevelopmentTeam = Q4SY8DMFN5; + LastSwiftMigration = 0800; + SystemCapabilities = { + com.apple.Keychain = { + enabled = 0; + }; + }; }; }; }; @@ -329,8 +336,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -352,7 +361,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -365,11 +374,14 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = Q4SY8DMFN5; FRAMEWORK_SEARCH_PATHS = "$(PROJECT_DIR)/Carthage/Build/iOS"; INFOPLIST_FILE = SampleApplication/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sample; PRODUCT_NAME = SampleApplication; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = 1; }; name = ProductionDebug; @@ -387,8 +399,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -404,9 +418,10 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -416,11 +431,14 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = Q4SY8DMFN5; FRAMEWORK_SEARCH_PATHS = "$(PROJECT_DIR)/Carthage/Build/iOS"; INFOPLIST_FILE = SampleApplication/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sample; PRODUCT_NAME = SampleApplication; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = 1; }; name = ProductionRelease; @@ -438,8 +456,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -461,7 +481,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -483,8 +503,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -500,9 +522,10 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -512,11 +535,14 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = Q4SY8DMFN5; FRAMEWORK_SEARCH_PATHS = "$(PROJECT_DIR)/Carthage/Build/iOS"; INFOPLIST_FILE = SampleApplication/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sample; PRODUCT_NAME = SampleApplication; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = 1; }; name = SandboxDebug; @@ -525,11 +551,14 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = Q4SY8DMFN5; FRAMEWORK_SEARCH_PATHS = "$(PROJECT_DIR)/Carthage/Build/iOS"; INFOPLIST_FILE = SampleApplication/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sample; PRODUCT_NAME = SampleApplication; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = 1; }; name = SandboxRelease; diff --git a/SampleApplication.xcodeproj/xcshareddata/xcschemes/SampleApplication.xcscheme b/SampleApplication.xcodeproj/xcshareddata/xcschemes/SampleApplication.xcscheme index f97369a..90a877c 100644 --- a/SampleApplication.xcodeproj/xcshareddata/xcschemes/SampleApplication.xcscheme +++ b/SampleApplication.xcodeproj/xcshareddata/xcschemes/SampleApplication.xcscheme @@ -1,6 +1,6 @@ Bool { - self.window = UIWindow(frame: UIScreen.mainScreen().bounds) + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + self.window = UIWindow(frame: UIScreen.main.bounds) guard let window = self.window else { return false @@ -36,8 +36,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate { - returns: A boolean indicating if the application can handle the URL resource or continue a user activity. */ - func application(application: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { - guard let window = self.window, rootViewController = window.rootViewController, loginViewController = rootViewController as? LoginViewController else { + func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { + guard let window = self.window, let rootViewController = window.rootViewController, let loginViewController = rootViewController as? LoginViewController else { return false } diff --git a/SampleApplication/ViewController/LoginViewController/LoginViewController.swift b/SampleApplication/ViewController/LoginViewController/LoginViewController.swift index 7348e34..7322f6e 100644 --- a/SampleApplication/ViewController/LoginViewController/LoginViewController.swift +++ b/SampleApplication/ViewController/LoginViewController/LoginViewController.swift @@ -24,19 +24,19 @@ class LoginViewController: UIViewController, SFSafariViewControllerDelegate { - parameter sender: The pressed login button. */ - @IBAction func didTapLoginButton(sender: AnyObject) { + @IBAction func didTapLoginButton(_ sender: AnyObject) { self.client = UpholdClient() - self.loginButton.enabled = false + self.loginButton.isEnabled = false let scopes: [String] = ["cards:read", "user:read"] - self.state = String(format: "oauth2:%@", NSUUID().UUIDString) + self.state = String(format: "oauth2:%@", UUID().uuidString) - guard let client = self.client, state = self.state else { + guard let client = self.client, let state = self.state else { self.handleError() return } - self.authorizationViewController = client.beginAuthorization(self, clientId: self.CLIENT_ID, scopes: scopes, state: state) + self.authorizationViewController = client.beginAuthorization(applicationViewController: self, clientId: self.CLIENT_ID, scopes: scopes, state: state) guard let authorizationViewController = self.authorizationViewController else { return @@ -50,31 +50,31 @@ class LoginViewController: UIViewController, SFSafariViewControllerDelegate { - parameter url: Authorization URL. */ - func completeAuthorization(url: NSURL) { + func completeAuthorization(_ url: URL) { let userViewController = UserViewController() - guard authorizationViewController = self.authorizationViewController, client = self.client, state = self.state else { + guard let authorizationViewController = self.authorizationViewController, let client = self.client, let state = self.state else { return self.handleError() } - client.completeAuthorization(authorizationViewController, clientId: self.CLIENT_ID, clientSecret: self.CLIENT_SECRET, grantType: "authorization_code", state: state, uri: url).then { (response: AuthenticationResponse) -> () in + client.completeAuthorization(authorizationViewController: authorizationViewController, clientId: self.CLIENT_ID, clientSecret: self.CLIENT_SECRET, grantType: "authorization_code", state: state, uri: url).then { (response: AuthenticationResponse) -> Void in userViewController.bearerToken = response.accessToken - self.presentViewController(userViewController, animated: true, completion: nil) - }.error { (error: ErrorType) -> Void in + self.present(userViewController, animated: true, completion: nil) + }.catch(execute: { (_: Error) in self.handleError() - } + }) } /** Handles login errors. */ func handleError() { - let alertController = UIAlertController(title: String(NSLocalizedString("login-view-controller.alert-title-login-error", comment: "Login Error.")), message: String(NSLocalizedString("global.unknown-error", comment: "Something went wrong.")), preferredStyle: .Alert) - self.loginButton.enabled = true + let alertController = UIAlertController(title: String(NSLocalizedString("login-view-controller.alert-title-login-error", comment: "Login Error.")), message: String(NSLocalizedString("global.unknown-error", comment: "Something went wrong.")), preferredStyle: .alert) + self.loginButton.isEnabled = true - alertController.addAction(UIAlertAction(title: String(NSLocalizedString("global.dismiss", comment: "Dismiss.")), style: .Default, handler: nil)) - self.presentViewController(alertController, animated: true, completion:nil) + alertController.addAction(UIAlertAction(title: String(NSLocalizedString("global.dismiss", comment: "Dismiss.")), style: .default, handler: nil)) + self.present(alertController, animated: true, completion: nil) } /** @@ -82,8 +82,8 @@ class LoginViewController: UIViewController, SFSafariViewControllerDelegate { - parameter controller: The view controller. */ - func safariViewControllerDidFinish(controller: SFSafariViewController) { - self.loginButton.enabled = true + func safariViewControllerDidFinish(_ controller: SFSafariViewController) { + self.loginButton.isEnabled = true } } diff --git a/SampleApplication/ViewController/UserViewController/UserViewController.swift b/SampleApplication/ViewController/UserViewController/UserViewController.swift index e01b9f2..9556d4d 100644 --- a/SampleApplication/ViewController/UserViewController/UserViewController.swift +++ b/SampleApplication/ViewController/UserViewController/UserViewController.swift @@ -22,7 +22,7 @@ class UserViewController: UIViewController { return } - UIApplication.sharedApplication().networkActivityIndicatorVisible = true + UIApplication.shared.isNetworkActivityIndicatorVisible = true self.authenticatedLabel.text = String(NSLocalizedString("user-view-controller.fetching-data", comment: "Fetching data.")) @@ -30,30 +30,30 @@ class UserViewController: UIViewController { let client = UpholdClient(bearerToken: bearerToken) client.getUser().always { () -> Void in - UIApplication.sharedApplication().networkActivityIndicatorVisible = false + UIApplication.shared.isNetworkActivityIndicatorVisible = false }.then { (user: User) -> Promise<[Card]> in self.user = user return user.getCards() - }.then { (cards: [Card]) -> () in - guard let user = self.user, firstName = user.firstName else { + }.then { (cards: [Card]) -> Void in + guard let user = self.user, let firstName = user.firstName else { return } self.authenticatedLabel.text = String(format: NSLocalizedString("user-view-controller.presenting-data", comment: "Presenting data."), firstName, cards.count) - }.error { (error: ErrorType) -> Void in + }.catch(execute: { (_: Error) in self.handleError() - } + }) } /** Handles login errors. */ func handleError() { - let alertController = UIAlertController(title: String(NSLocalizedString("user-view-controller.alert-title-fetching-error", comment: "Fetching error.")), message: String(NSLocalizedString("global.unknown-error", comment: "Something went wrong.")), preferredStyle: .Alert) + let alertController = UIAlertController(title: String(NSLocalizedString("user-view-controller.alert-title-fetching-error", comment: "Fetching error.")), message: String(NSLocalizedString("global.unknown-error", comment: "Something went wrong.")), preferredStyle: .alert) - alertController.addAction(UIAlertAction(title: String(NSLocalizedString("global.dismiss", comment: "Dismiss.")), style: .Default, handler: nil)) - self.presentViewController(alertController, animated: true, completion:nil) + alertController.addAction(UIAlertAction(title: String(NSLocalizedString("global.dismiss", comment: "Dismiss.")), style: .default, handler: nil)) + self.present(alertController, animated: true, completion: nil) } } diff --git a/Source/Client/AuthorizationViewController.swift b/Source/Client/AuthorizationViewController.swift index 9589f98..9cc1070 100644 --- a/Source/Client/AuthorizationViewController.swift +++ b/Source/Client/AuthorizationViewController.swift @@ -3,7 +3,7 @@ import SafariServices import UIKit /// Uphold authorization view controller. -public class AuthorizationViewController: SFSafariViewController { +open class AuthorizationViewController: SFSafariViewController { /** Constructor. @@ -11,8 +11,8 @@ public class AuthorizationViewController: SFSafariViewController { - parameter URL: The authorization URL. - parameter entersReaderIfAvailable: A boolean that defines if reader mode should be entered automatically when it is available for the webpage. */ - override init(URL: NSURL, entersReaderIfAvailable: Bool) { - super.init(URL: URL, entersReaderIfAvailable: entersReaderIfAvailable) + override init(url URL: URL, entersReaderIfAvailable: Bool) { + super.init(url: URL, entersReaderIfAvailable: entersReaderIfAvailable) } } diff --git a/Source/Client/SessionManager.swift b/Source/Client/SessionManager.swift index dd1761d..e016558 100644 --- a/Source/Client/SessionManager.swift +++ b/Source/Client/SessionManager.swift @@ -2,7 +2,7 @@ import Foundation import KeychainSwift /// Session manager. -public class SessionManager { +open class SessionManager { /// The keychain key to access the bearer token. static let KEYCHAIN_TOKEN_KEY = "com.uphold.sdk.token" @@ -14,14 +14,14 @@ public class SessionManager { let keychain: KeychainSwift /// Queue to manage concurrency. - let lockQueue: dispatch_queue_t + let lockQueue: DispatchQueue /** Constructor. */ private init() { self.keychain = KeychainSwift() - self.lockQueue = dispatch_queue_create(GlobalConfigurations.BUNDLE_NAME, nil) + self.lockQueue = DispatchQueue(label: GlobalConfigurations.BUNDLE_NAME, attributes: []) self.invalidateSession() } @@ -47,7 +47,7 @@ public class SessionManager { func setBearerToken(token: String) { self.invalidateSession() - dispatch_sync(self.lockQueue) { + _ = self.lockQueue.sync { self.keychain.set(token, forKey: SessionManager.KEYCHAIN_TOKEN_KEY) } } @@ -56,7 +56,7 @@ public class SessionManager { Deletes the bearer token from the keychain. */ func invalidateSession() { - dispatch_sync(self.lockQueue) { + _ = self.lockQueue.sync { self.keychain.delete(SessionManager.KEYCHAIN_TOKEN_KEY) } } diff --git a/Source/Client/UpholdClient.swift b/Source/Client/UpholdClient.swift index c2ed8f3..5aeacbd 100644 --- a/Source/Client/UpholdClient.swift +++ b/Source/Client/UpholdClient.swift @@ -5,13 +5,13 @@ import SwiftClient import UIKit /// Uphold client. -public class UpholdClient: Client { +open class UpholdClient: Client { /// The SwiftLint rules that must be disabled. // swiftlint:disable force_try /// The Uphold user's token. - public private(set) var token: Token + open private(set) var token: Token /** Constructor. @@ -21,7 +21,7 @@ public class UpholdClient: Client { super.init() - self.baseUrl(GlobalConfigurations.UPHOLD_API_URL) + _ = self.baseUrl(url: GlobalConfigurations.UPHOLD_API_URL) } /** @@ -35,7 +35,7 @@ public class UpholdClient: Client { self.token = Token(bearerToken: bearerToken) if let token = token.bearerToken { - SessionManager.sharedInstance.setBearerToken(token) + SessionManager.sharedInstance.setBearerToken(token: token) } } @@ -49,13 +49,13 @@ public class UpholdClient: Client { - returns: The authorization view controller presented modally. */ - public func beginAuthorization(applicationViewController: UIViewController, clientId: String, scopes: [String], state: String) -> AuthorizationViewController? { - let url = String(format: "%@/authorize/%@?scope=%@&state=%@", GlobalConfigurations.UPHOLD_AUTHORIZATION_SERVER_URL, clientId, scopes.joinWithSeparator(" "), state) + open func beginAuthorization(applicationViewController: UIViewController, clientId: String, scopes: [String], state: String) -> AuthorizationViewController? { + let url = String(format: "%@/authorize/%@?scope=%@&state=%@", GlobalConfigurations.UPHOLD_AUTHORIZATION_SERVER_URL, clientId, scopes.joined(separator: " "), state) /// This try forces a runtime exception whenever the URL is not valid after escaping it. - let authorizationViewController = try! AuthorizationViewController(URL: URLUtils.escapeURL(url), entersReaderIfAvailable: false) + let authorizationViewController = try! AuthorizationViewController(url: URLUtils.escapeURL(url: url), entersReaderIfAvailable: false) - applicationViewController.presentViewController(authorizationViewController, animated: true, completion: nil) + applicationViewController.present(authorizationViewController, animated: true, completion: nil) return authorizationViewController } @@ -72,12 +72,12 @@ public class UpholdClient: Client { - returns: A promise with the AuthenticationResponse. */ - public func completeAuthorization(authorizationViewController: AuthorizationViewController, clientId: String, clientSecret: String, grantType: String, state: String, uri: NSURL) -> Promise { + open func completeAuthorization(authorizationViewController: AuthorizationViewController, clientId: String, clientSecret: String, grantType: String, state: String, uri: URL) -> Promise { let adapter = self.token.adapter - authorizationViewController.dismissViewControllerAnimated(true, completion: nil) + authorizationViewController.dismiss(animated: true, completion: nil) - guard let queryParameters = NSURLComponents(URL: uri, resolvingAgainstBaseURL: false)?.queryItems, stateParameter = queryParameters.filter({ parameter in parameter.name == "state" }).first, responseState = stateParameter.value else { + guard let queryParameters = URLComponents(url: uri, resolvingAgainstBaseURL: false)?.queryItems, let stateParameter = queryParameters.filter({ parameter in parameter.name == "state" }).first, let responseState = stateParameter.value else { return Promise(error: UnexpectedResponseError(message: "URL query parameter state should not be nil.")) } @@ -85,11 +85,11 @@ public class UpholdClient: Client { return Promise(error: StateMatchError(message: "URL query parameter state does not match.")) } - guard let responseCode = queryParameters.filter({ parameter in parameter.name == "code" }).first, code = responseCode.value else { + guard let responseCode = queryParameters.filter({ parameter in parameter.name == "code" }).first, let code = responseCode.value else { return Promise(error: UnexpectedResponseError(message: "URL query parameter code should not be nil.")) } - return adapter.buildResponse(adapter.buildRequest(OAuth2Service.requestToken(clientId, clientSecret: clientSecret, code: code, grantType: grantType))) + return adapter.buildResponse(request: adapter.buildRequest(request: OAuth2Service.requestToken(clientId: clientId, clientSecret: clientSecret, code: code, grantType: grantType))) } /** @@ -97,7 +97,7 @@ public class UpholdClient: Client { - returns: The reserve object. */ - public func getReserve() -> Reserve { + open func getReserve() -> Reserve { return Reserve() } @@ -106,10 +106,10 @@ public class UpholdClient: Client { - returns: A promise with all exchanges rates for all currency pairs. */ - public func getTickers() -> Promise<[Rate]> { + open func getTickers() -> Promise<[Rate]> { let adapter = self.token.adapter - return adapter.buildResponse(adapter.buildRequest(TickerService.getAllTickers())) + return adapter.buildResponse(request: adapter.buildRequest(request: TickerService.getAllTickers())) } /** @@ -119,10 +119,10 @@ public class UpholdClient: Client { - returns: A promise with all exchanges rates relative to a given currency. */ - public func getTickersByCurrency(currency: String) -> Promise<[Rate]> { + open func getTickersByCurrency(currency: String) -> Promise<[Rate]> { let adapter = self.token.adapter - return adapter.buildResponse(adapter.buildRequest(TickerService.getAllTickersByCurrency(currency))) + return adapter.buildResponse(request: adapter.buildRequest(request: TickerService.getAllTickersByCurrency(currency: currency))) } /** @@ -130,14 +130,14 @@ public class UpholdClient: Client { - returns: A promise with the user. */ - public func getUser() -> Promise { + open func getUser() -> Promise { return self.token.getUser() } /** Invalidates the client session. */ - public func invalidateSession() { + open func invalidateSession() { SessionManager.sharedInstance.invalidateSession() } diff --git a/Source/Client/UpholdClientErrorHandling.swift b/Source/Client/UpholdClientErrorHandling.swift index 44680cd..297a781 100644 --- a/Source/Client/UpholdClientErrorHandling.swift +++ b/Source/Client/UpholdClientErrorHandling.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// Uphold client error handling. -public class UpholdClientErrorHandling { +open class UpholdClientErrorHandling { /** Handles the uphold client errors. @@ -11,26 +11,26 @@ public class UpholdClientErrorHandling { - returns: The UpholdClientError child for each ResponseType. */ - public static func handleError(response: Response) -> UpholdClientError { + open static func handleError(response: Response) -> UpholdClientError { switch (response.status) { - case Response.ResponseType.BadRequest: + case Response.ResponseType.badRequest: return BadRequestError(code: 400, message: "HTTP error 400 - Bad request.", response: response) - case Response.ResponseType.Unauthorized: + case Response.ResponseType.unauthorized: return AuthenticationError(code: 401, message: "HTTP error 401 - Unauthorized.", response: response) - case Response.ResponseType.NotFound: + case Response.ResponseType.notFound: return NotFoundError(code: 404, message: String(format: "HTTP error 404 - Object or route not found: %@.", response.request.url), response: response) - case Response.ResponseType.PreConditionFail: + case Response.ResponseType.preConditionFail: return BadRequestError(code: 412, message: "HTTP error 412 - Precondition failed.", response: response) - case Response.ResponseType.AuthenticationTimeout: + case Response.ResponseType.authenticationTimeout: return BadRequestError(code: 419, message: "HTTP error 419 - Requested range not satisfiable.", response: response) - case Response.ResponseType.TooManyRequests: - return ApiLimitExceedError(code: 429, message: String(format: "HTTP error 429 - You have exceeded Uphold's API rate limit of %@ requests. Current time window ends in %@ seconds.", Header.getRateLimitValue(response.headers)!, Header.getSecondsUntilRateLimitReset(response.headers)!), response: response) + case Response.ResponseType.tooManyRequests: + return ApiLimitExceedError(code: 429, message: String(format: "HTTP error 429 - You have exceeded Uphold's API rate limit of %@ requests. Current time window ends in %@ seconds.", Header.getRateLimitValue(headers: response.headers)!, Header.getSecondsUntilRateLimitReset(headers: response.headers)!), response: response) default: return UnhandledError(code: nil, message: "Invalid status code.", response: response) diff --git a/Source/Client/UpholdRestAdapter.swift b/Source/Client/UpholdRestAdapter.swift index 1a5de14..0890a85 100644 --- a/Source/Client/UpholdRestAdapter.swift +++ b/Source/Client/UpholdRestAdapter.swift @@ -4,7 +4,7 @@ import PromiseKit import SwiftClient /// Uphold REST adapter. -public class UpholdRestAdapter { +open class UpholdRestAdapter { /** Constructor. @@ -19,14 +19,14 @@ public class UpholdRestAdapter { - returns: The configured HTTP request. */ - public func buildRequest(request: Request) -> Request { + open func buildRequest(request: Request) -> Request { guard let bearerToken = SessionManager.sharedInstance.getBearerToken() else { - return request.set(Header.getDefaultHeaders()) + return request.set(headers: Header.getDefaultHeaders()) } - request.set(Header.getDefaultHeaders()) + _ = request.set(headers: Header.getDefaultHeaders()) - return request.set(Header.buildAuthorizationHeader(bearerToken)) + return request.set(headers: Header.buildAuthorizationHeader(token: bearerToken)) } /** @@ -36,22 +36,22 @@ public class UpholdRestAdapter { - returns: A promise of Response. */ - public func buildEmptyResponse(request: Request) -> Promise { + open func buildEmptyResponse(request: Request) -> Promise { return Promise { fulfill, reject in - request.end({ (response: Response) -> Void in - if (response.basicStatus != Response.BasicResponseType.OK) { - reject(UpholdClientErrorHandling.handleError(response)) + request.end(done: { (response: Response) -> Void in + if (response.basicStatus != Response.BasicResponseType.ok) { + reject(UpholdClientErrorHandling.handleError(response: response)) return } - if let body = response.text where !body.isEmpty { + if let body = response.text, !body.isEmpty { reject(LogicError(code: nil, message: "Response body should be empty.")) } else { fulfill(response) } - }, onError: { (error: NSError) -> Void in + }, onError: { (error: Error) -> Void in reject(error) }) } @@ -64,11 +64,11 @@ public class UpholdRestAdapter { - returns: A promise of T object. */ - public func buildResponse(request: Request) -> Promise { + open func buildResponse(request: Request) -> Promise { return Promise { fulfill, reject in - request.end({ (response: Response) -> Void in - if (response.basicStatus != Response.BasicResponseType.OK) { - reject(UpholdClientErrorHandling.handleError(response)) + request.end(done: { (response: Response) -> Void in + if (response.basicStatus != Response.BasicResponseType.ok) { + reject(UpholdClientErrorHandling.handleError(response: response)) return } @@ -79,14 +79,14 @@ public class UpholdRestAdapter { return } - guard let object: T = Mapper().map(body) else { + guard let object: T = Mapper().map(JSONString: body) else { reject(LogicError(code: nil, message: "Failed to map the JSON object.")) return } fulfill(object) - }) { (error: NSError) -> Void in + }) { (error: Error) -> Void in reject(error) } } @@ -99,11 +99,11 @@ public class UpholdRestAdapter { - returns: A promise of an array of T objects. */ - public func buildResponse(request: Request) -> Promise<[T]> { + open func buildResponse(request: Request) -> Promise<[T]> { return Promise { fulfill, reject in - request.end({ (response: Response) -> Void in - if (response.basicStatus != Response.BasicResponseType.OK) { - reject(UpholdClientErrorHandling.handleError(response)) + request.end(done: { (response: Response) -> Void in + if (response.basicStatus != Response.BasicResponseType.ok) { + reject(UpholdClientErrorHandling.handleError(response: response)) return } @@ -114,14 +114,14 @@ public class UpholdRestAdapter { return } - guard let object: [T] = Mapper().mapArray(body) else { + guard let object: [T] = Mapper().mapArray(JSONString: body) else { reject(LogicError(code: nil, message: "Failed to map the JSON object.")) return } fulfill(object) - }) { (error: NSError) -> Void in + }) { (error: Error) -> Void in reject(error) } } diff --git a/Source/Configurations/GlobalConfigurations.swift b/Source/Configurations/GlobalConfigurations.swift index 1c2465d..cb4c17b 100644 --- a/Source/Configurations/GlobalConfigurations.swift +++ b/Source/Configurations/GlobalConfigurations.swift @@ -1,21 +1,21 @@ import Foundation /// The global SDK configurations class. -public class GlobalConfigurations { +open class GlobalConfigurations { /// Uphold's Swift SDK bundle name. - public static let BUNDLE_NAME: String = NSBundle.mainBundle().bundleIdentifier == nil ? "com.uphold.uphold-swift-sdk" : NSBundle.mainBundle().bundleIdentifier! + open static let BUNDLE_NAME: String = Bundle.main.bundleIdentifier == nil ? "com.uphold.uphold-swift-sdk" : Bundle.main.bundleIdentifier! /// Uphold's Swift SDK github repository URL. - public static let SDK_GITHUB_URL: String = "https://github.com/uphold/uphold-sdk-ios" + open static let SDK_GITHUB_URL: String = "https://github.com/uphold/uphold-sdk-ios" /// Uphold's Swift SDK current version. - public static let UPHOLD_SDK_VERSION: String = ResourcesUtil.getValueFromInfoPlist("CFBundleShortVersionString") + open static let UPHOLD_SDK_VERSION: String = ResourcesUtil.getValueFromInfoPlist(key: "CFBundleShortVersionString") /// Uphold's API URL. - public static let UPHOLD_API_URL: String = ResourcesUtil.getValueFromConfigurationsPlist("API_URL") + open static let UPHOLD_API_URL: String = ResourcesUtil.getValueFromConfigurationsPlist(key: "API_URL") /// Uphold's authorization server URL. - public static let UPHOLD_AUTHORIZATION_SERVER_URL: String = ResourcesUtil.getValueFromConfigurationsPlist("AUTHORIZATION_SERVER_URL") + open static let UPHOLD_AUTHORIZATION_SERVER_URL: String = ResourcesUtil.getValueFromConfigurationsPlist(key: "AUTHORIZATION_SERVER_URL") } diff --git a/Source/ErrorHandling/ApiLimitExceedError.swift b/Source/ErrorHandling/ApiLimitExceedError.swift index 5d863a1..cb58f20 100644 --- a/Source/ErrorHandling/ApiLimitExceedError.swift +++ b/Source/ErrorHandling/ApiLimitExceedError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// ApiLimitExceedError error. -public class ApiLimitExceedError: UpholdClientError { +open class ApiLimitExceedError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/AuthenticationError.swift b/Source/ErrorHandling/AuthenticationError.swift index 95fb272..21d8480 100644 --- a/Source/ErrorHandling/AuthenticationError.swift +++ b/Source/ErrorHandling/AuthenticationError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// AuthenticationError error. -public class AuthenticationError: UpholdClientError { +open class AuthenticationError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/AuthenticationRequiredError.swift b/Source/ErrorHandling/AuthenticationRequiredError.swift index 12307fc..30d2d1f 100644 --- a/Source/ErrorHandling/AuthenticationRequiredError.swift +++ b/Source/ErrorHandling/AuthenticationRequiredError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// Authentication required error. -public class AuthenticationRequiredError: UpholdClientError { +open class AuthenticationRequiredError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/BadRequestError.swift b/Source/ErrorHandling/BadRequestError.swift index 3b8f4e9..eb0bb36 100644 --- a/Source/ErrorHandling/BadRequestError.swift +++ b/Source/ErrorHandling/BadRequestError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// BadRequestError error. -public class BadRequestError: UpholdClientError { +open class BadRequestError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/ConfigurationMissingError.swift b/Source/ErrorHandling/ConfigurationMissingError.swift index 7b1783f..81e5f88 100644 --- a/Source/ErrorHandling/ConfigurationMissingError.swift +++ b/Source/ErrorHandling/ConfigurationMissingError.swift @@ -1,7 +1,7 @@ import Foundation /// Configuration missing error. -public class ConfigurationMissingError: UpholdClientError { +open class ConfigurationMissingError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/LogicError.swift b/Source/ErrorHandling/LogicError.swift index ab80393..60aca57 100644 --- a/Source/ErrorHandling/LogicError.swift +++ b/Source/ErrorHandling/LogicError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// LogicError error. -public class LogicError: UpholdClientError { +open class LogicError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/MalformedUrlError.swift b/Source/ErrorHandling/MalformedUrlError.swift index e5813d7..b77c29d 100644 --- a/Source/ErrorHandling/MalformedUrlError.swift +++ b/Source/ErrorHandling/MalformedUrlError.swift @@ -1,7 +1,7 @@ import Foundation /// MalformedUrlError error. -public class MalformedUrlError: UpholdClientError { +open class MalformedUrlError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/NotFoundError.swift b/Source/ErrorHandling/NotFoundError.swift index 7e0ddb0..c74b99f 100644 --- a/Source/ErrorHandling/NotFoundError.swift +++ b/Source/ErrorHandling/NotFoundError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// NotFoundError error. -public class NotFoundError: UpholdClientError { +open class NotFoundError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/StateMatchError.swift b/Source/ErrorHandling/StateMatchError.swift index 14a5852..2c204aa 100644 --- a/Source/ErrorHandling/StateMatchError.swift +++ b/Source/ErrorHandling/StateMatchError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// State match error. -public class StateMatchError: UpholdClientError { +open class StateMatchError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/UnexpectedResponseError.swift b/Source/ErrorHandling/UnexpectedResponseError.swift index 870dc71..166d137 100644 --- a/Source/ErrorHandling/UnexpectedResponseError.swift +++ b/Source/ErrorHandling/UnexpectedResponseError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// UnexpectedResponseError error. -public class UnexpectedResponseError: UpholdClientError { +open class UnexpectedResponseError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/UnhandledError.swift b/Source/ErrorHandling/UnhandledError.swift index 786d931..a1a3e0b 100644 --- a/Source/ErrorHandling/UnhandledError.swift +++ b/Source/ErrorHandling/UnhandledError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// UnhandledError error. -public class UnhandledError: UpholdClientError { +open class UnhandledError: UpholdClientError { /** Constructor. diff --git a/Source/ErrorHandling/UpholdClientError.swift b/Source/ErrorHandling/UpholdClientError.swift index 769389f..f2685ee 100644 --- a/Source/ErrorHandling/UpholdClientError.swift +++ b/Source/ErrorHandling/UpholdClientError.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// UpholdClientError error. -public class UpholdClientError: ErrorType, CustomStringConvertible { +open class UpholdClientError: Error, CustomStringConvertible { /// The HTTP status code. public final var code: Int? diff --git a/Source/Model/Account.swift b/Source/Model/Account.swift index 83ff24e..ef3461a 100644 --- a/Source/Model/Account.swift +++ b/Source/Model/Account.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Account model. -public class Account: Mappable { +open class Account: Mappable { /// The currency. public private(set) final var currency: String? @@ -43,7 +43,7 @@ public class Account: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -51,7 +51,7 @@ public class Account: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.currency <- map["currency"] self.id <- map["id"] self.label <- map["label"] diff --git a/Source/Model/AuthenticationRequest.swift b/Source/Model/AuthenticationRequest.swift index 9de3e65..4839c7c 100644 --- a/Source/Model/AuthenticationRequest.swift +++ b/Source/Model/AuthenticationRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Authentication request model. -public class AuthenticationRequest: Mappable { +open class AuthenticationRequest: Mappable { /// The description for the authentication request. public private(set) final var description: String? @@ -23,7 +23,7 @@ public class AuthenticationRequest: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class AuthenticationRequest: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.description <- map["description"] } diff --git a/Source/Model/AuthenticationResponse.swift b/Source/Model/AuthenticationResponse.swift index 4d01082..9456b56 100644 --- a/Source/Model/AuthenticationResponse.swift +++ b/Source/Model/AuthenticationResponse.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Authentication response model. -public class AuthenticationResponse: Mappable { +open class AuthenticationResponse: Mappable { /// The user access token. public private(set) final var accessToken: String? @@ -38,7 +38,7 @@ public class AuthenticationResponse: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -46,7 +46,7 @@ public class AuthenticationResponse: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.accessToken <- map["access_token"] self.expiresIn <- map["expires_in"] self.scope <- map["scope"] diff --git a/Source/Model/Balance.swift b/Source/Model/Balance.swift index fef177f..9dd6031 100644 --- a/Source/Model/Balance.swift +++ b/Source/Model/Balance.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Balance model. -public class Balance: Mappable { +open class Balance: Mappable { /// The user balance. public private(set) final var balances: UserBalance? @@ -23,7 +23,7 @@ public class Balance: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class Balance: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.balances <- map["balances"] } diff --git a/Source/Model/Balance/Currency.swift b/Source/Model/Balance/Currency.swift index 55550eb..2562267 100644 --- a/Source/Model/Balance/Currency.swift +++ b/Source/Model/Balance/Currency.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Currency model. -public class Currency: Mappable { +open class Currency: Mappable { /// The amount of the currency. public private(set) final var amount: String? @@ -38,7 +38,7 @@ public class Currency: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -46,7 +46,7 @@ public class Currency: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.amount <- map["amount"] self.balance <- map["balance"] self.currency <- map["currency"] diff --git a/Source/Model/Balance/UserBalance.swift b/Source/Model/Balance/UserBalance.swift index 95623be..dae9141 100644 --- a/Source/Model/Balance/UserBalance.swift +++ b/Source/Model/Balance/UserBalance.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Currency model. -public class UserBalance: Mappable { +open class UserBalance: Mappable { /// The list of the currencies. public private(set) final var currencies: [String: Currency]? @@ -28,7 +28,7 @@ public class UserBalance: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -36,7 +36,7 @@ public class UserBalance: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.currencies <- map["currencies"] self.total <- map["total"] } diff --git a/Source/Model/BaseModel.swift b/Source/Model/BaseModel.swift index 2ab7acc..635fb44 100644 --- a/Source/Model/BaseModel.swift +++ b/Source/Model/BaseModel.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// Base model. -public class BaseModel { +open class BaseModel { /// The Uphold REST adapter. public internal(set) final var adapter: UpholdRestAdapter diff --git a/Source/Model/Card.swift b/Source/Model/Card.swift index 4492ad2..410ab7e 100644 --- a/Source/Model/Card.swift +++ b/Source/Model/Card.swift @@ -4,7 +4,7 @@ import PromiseKit import SwiftClient /// Card model. -public class Card: BaseModel, Mappable { +open class Card: BaseModel, Mappable { /// The id of the card. public private(set) final var id: String? @@ -65,7 +65,7 @@ public class Card: BaseModel, Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -73,7 +73,7 @@ public class Card: BaseModel, Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.id <- map["id"] self.address <- map["address"] self.available <- map["available"] @@ -92,14 +92,14 @@ public class Card: BaseModel, Mappable { - returns: A promise with the created address. */ - public func createAddress(addressRequest: AddressRequest) -> Promise
{ + open func createAddress(addressRequest: AddressRequest) -> Promise
{ guard let id = self.id else { return Promise
(error: UnexpectedResponseError(message: "Card id should not be nil.")) } - let request = self.adapter.buildRequest(UserCardService.createCardAddress(id, addressRequest: Mapper().toJSON(addressRequest))) + let request = self.adapter.buildRequest(request: UserCardService.createCardAddress(cardId: id, addressRequest: Mapper().toJSON(addressRequest))) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -109,8 +109,8 @@ public class Card: BaseModel, Mappable { - returns: A promise with the transaction. */ - public func createTransaction(transactionRequest: TransactionRequest) -> Promise { - return createTransaction(false, transactionRequest: transactionRequest) + open func createTransaction(transactionRequest: TransactionRequest) -> Promise { + return createTransaction(commit: false, transactionRequest: transactionRequest) } /** @@ -121,14 +121,14 @@ public class Card: BaseModel, Mappable { - returns: A promise with the transaction. */ - public func createTransaction(commit: Bool, transactionRequest: TransactionRequest) -> Promise { + open func createTransaction(commit: Bool, transactionRequest: TransactionRequest) -> Promise { guard let id = self.id else { return Promise(error: UnexpectedResponseError(message: "Card id should not be nil.")) } - let request = self.adapter.buildRequest(UserCardService.createTransaction(id, commit: commit, transactionRequest: Mapper().toJSON(transactionRequest))) + let request = self.adapter.buildRequest(request: UserCardService.createTransaction(cardId: id, commit: commit, transactionRequest: Mapper().toJSON(transactionRequest))) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -136,7 +136,7 @@ public class Card: BaseModel, Mappable { - returns: A paginator with the list of transactions for the current card. */ - public func getTransactions() -> Paginator { + open func getTransactions() -> Paginator { guard let id = self.id else { let error = UnexpectedResponseError(message: "Card id should not be nil.") @@ -144,20 +144,20 @@ public class Card: BaseModel, Mappable { return Promise(error: error) }, elements: Promise<[Transaction]>(error: error), - hasNextPageClosure: { (currentPage) -> Promise in + hasNextPageClosure: { (_) -> Promise in return Promise(error: error) }, - nextPageClosure: { (range) -> Promise<[Transaction]> in + nextPageClosure: { (_) -> Promise<[Transaction]> in return Promise<[Transaction]>(error: error) }) } - let request = self.adapter.buildRequest(UserCardService.getUserCardTransactions(id, range: Header.buildRangeHeader(Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) + let request = self.adapter.buildRequest(request: UserCardService.getUserCardTransactions(cardId: id, range: Header.buildRangeHeader(start: Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) let paginator: Paginator = Paginator(countClosure: { () -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(UserCardService.getUserCardTransactions(id, range: Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: UserCardService.getUserCardTransactions(cardId: id, range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Type header should not be nil.")) return @@ -167,11 +167,11 @@ public class Card: BaseModel, Mappable { }) } }, - elements: self.adapter.buildResponse(request), + elements: self.adapter.buildResponse(request: request), hasNextPageClosure: { (currentPage) -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(UserCardService.getUserCardTransactions(id, range: Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: UserCardService.getUserCardTransactions(cardId: id, range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Type header should not be nil.")) return @@ -182,8 +182,8 @@ public class Card: BaseModel, Mappable { } }, nextPageClosure: { (range) -> Promise<[Transaction]> in - let request = self.adapter.buildRequest(UserCardService.getUserCardTransactions(id, range: range)) - let promise: Promise<[Transaction]> = self.adapter.buildResponse(request) + let request = self.adapter.buildRequest(request: UserCardService.getUserCardTransactions(cardId: id, range: range)) + let promise: Promise<[Transaction]> = self.adapter.buildResponse(request: request) return promise }) @@ -198,14 +198,14 @@ public class Card: BaseModel, Mappable { - returns: A promise with the card updated. */ - public func update(updateFields: [String: AnyObject]) -> Promise { + open func update(updateFields: [String: Any]) -> Promise { guard let id = self.id else { return Promise(error: UnexpectedResponseError(message: "Card id should not be nil.")) } - let request = self.adapter.buildRequest(UserCardService.updateCard(id, updateFields: updateFields)) + let request = self.adapter.buildRequest(request: UserCardService.updateCard(cardId: id, updateFields: updateFields)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } } diff --git a/Source/Model/Card/Address.swift b/Source/Model/Card/Address.swift index ad2fb06..59459e7 100644 --- a/Source/Model/Card/Address.swift +++ b/Source/Model/Card/Address.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Card address model. -public class Address: Mappable { +open class Address: Mappable { /// The id of the created address. public private(set) final var id: String? @@ -28,7 +28,7 @@ public class Address: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -36,7 +36,7 @@ public class Address: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.id <- map["id"] self.network <- map["network"] } diff --git a/Source/Model/Card/AddressRequest.swift b/Source/Model/Card/AddressRequest.swift index a9f03f5..ff6aff6 100644 --- a/Source/Model/Card/AddressRequest.swift +++ b/Source/Model/Card/AddressRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Card address request model. -public class AddressRequest: Mappable { +open class AddressRequest: Mappable { /// The network for the address to be created. public private(set) final var network: String? @@ -23,7 +23,7 @@ public class AddressRequest: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class AddressRequest: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.network <- map["network"] } diff --git a/Source/Model/Card/CardRequest.swift b/Source/Model/Card/CardRequest.swift index 967c980..0c94aad 100644 --- a/Source/Model/Card/CardRequest.swift +++ b/Source/Model/Card/CardRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Card request model. -public class CardRequest: Mappable { +open class CardRequest: Mappable { /// The currency of the card. public private(set) final var currency: String? @@ -44,7 +44,7 @@ public class CardRequest: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -52,7 +52,7 @@ public class CardRequest: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { currency <- map["currency"] label <- map["label"] settings <- map["settings"] diff --git a/Source/Model/Card/CardSettings.swift b/Source/Model/Card/CardSettings.swift index 442c534..4254133 100644 --- a/Source/Model/Card/CardSettings.swift +++ b/Source/Model/Card/CardSettings.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// CardSettings model. -public class CardSettings: Mappable { +open class CardSettings: Mappable { /// The position of the card. public private(set) final var position: Int? @@ -31,7 +31,7 @@ public class CardSettings: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -39,7 +39,7 @@ public class CardSettings: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { position <- map["position"] protected <- map["protected"] starred <- map["starred"] diff --git a/Source/Model/Card/NormalizedCard.swift b/Source/Model/Card/NormalizedCard.swift index d0fd54c..c46bf30 100644 --- a/Source/Model/Card/NormalizedCard.swift +++ b/Source/Model/Card/NormalizedCard.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Card normalized model. -public class NormalizedCard: Mappable { +open class NormalizedCard: Mappable { /// The amount available normalized. public private(set) final var available: String? @@ -33,7 +33,7 @@ public class NormalizedCard: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -41,7 +41,7 @@ public class NormalizedCard: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { available <- map["available"] balance <- map["balance"] currency <- map["currency"] diff --git a/Source/Model/Document.swift b/Source/Model/Document.swift index f43d86c..a314f10 100644 --- a/Source/Model/Document.swift +++ b/Source/Model/Document.swift @@ -28,7 +28,7 @@ public class Document: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** diff --git a/Source/Model/Rate.swift b/Source/Model/Rate.swift index 6582b4d..7c02a03 100644 --- a/Source/Model/Rate.swift +++ b/Source/Model/Rate.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Rate model. -public class Rate: Mappable { +open class Rate: Mappable { /// The rate ask. public private(set) final var ask: String? @@ -38,7 +38,7 @@ public class Rate: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -46,7 +46,7 @@ public class Rate: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { ask <- map["ask"] bid <- map["bid"] currency <- map["currency"] diff --git a/Source/Model/Reserve.swift b/Source/Model/Reserve.swift index 0659422..56a53d4 100644 --- a/Source/Model/Reserve.swift +++ b/Source/Model/Reserve.swift @@ -3,20 +3,20 @@ import PromiseKit import SwiftClient /// Reserve model. -public class Reserve: BaseModel { +open class Reserve: BaseModel { /** Gets the ledger. - returns: A paginator with the array of deposits. */ - public func getLedger() -> Paginator { - let request = self.adapter.buildRequest(ReserveService.getLedger(Header.buildRangeHeader(Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) + open func getLedger() -> Paginator { + let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) let paginator: Paginator = Paginator(countClosure: { () -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(ReserveService.getLedger(Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Type header should not be nil.")) return @@ -26,11 +26,11 @@ public class Reserve: BaseModel { }) } }, - elements: self.adapter.buildResponse(request), + elements: self.adapter.buildResponse(request: request), hasNextPageClosure: { (currentPage) -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(ReserveService.getLedger(Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Type header should not be nil.")) return @@ -41,8 +41,8 @@ public class Reserve: BaseModel { } }, nextPageClosure: { (range) -> Promise<[Deposit]> in - let request = self.adapter.buildRequest(ReserveService.getLedger(range)) - let promise: Promise<[Deposit]> = self.adapter.buildResponse(request) + let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: range)) + let promise: Promise<[Deposit]> = self.adapter.buildResponse(request: request) return promise }) @@ -55,10 +55,10 @@ public class Reserve: BaseModel { - returns: A promise with the reserve summary of all the obligations and assets within it. */ - public func getStatistics() -> Promise<[ReserveStatistics]> { - let request = self.adapter.buildRequest(ReserveService.getStatistics()) + open func getStatistics() -> Promise<[ReserveStatistics]> { + let request = self.adapter.buildRequest(request: ReserveService.getStatistics()) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -68,10 +68,10 @@ public class Reserve: BaseModel { - returns: A promise with the transaction. */ - public func getTransactionById(transactionId: String) -> Promise { - let request = self.adapter.buildRequest(ReserveService.getReserveTransactionById(transactionId)) + open func getTransactionById(transactionId: String) -> Promise { + let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactionById(transactionId: transactionId)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -79,13 +79,13 @@ public class Reserve: BaseModel { - returns: A paginator with the array of transactions. */ - public func getTransactions() -> Paginator { - let request = self.adapter.buildRequest(ReserveService.getReserveTransactions(Header.buildRangeHeader(Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) + open func getTransactions() -> Paginator { + let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) let paginator: Paginator = Paginator(countClosure: { () -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(ReserveService.getReserveTransactions(Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Type header should not be nil.")) return @@ -95,11 +95,11 @@ public class Reserve: BaseModel { }) } }, - elements: self.adapter.buildResponse(request), + elements: self.adapter.buildResponse(request: request), hasNextPageClosure: { (currentPage) -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(ReserveService.getReserveTransactions(Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Type header should not be nil.")) return @@ -110,8 +110,8 @@ public class Reserve: BaseModel { } }, nextPageClosure: { (range) -> Promise<[Transaction]> in - let request = self.adapter.buildRequest(ReserveService.getReserveTransactions(range)) - let promise: Promise<[Transaction]> = self.adapter.buildResponse(request) + let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: range)) + let promise: Promise<[Transaction]> = self.adapter.buildResponse(request: request) return promise }) diff --git a/Source/Model/Reserve/Deposit.swift b/Source/Model/Reserve/Deposit.swift index eb73097..845a866 100644 --- a/Source/Model/Reserve/Deposit.swift +++ b/Source/Model/Reserve/Deposit.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Deposit model. -public class Deposit: Mappable { +open class Deposit: Mappable { /// The date when the transaction was created. public private(set) final var createdAt: String? @@ -43,7 +43,7 @@ public class Deposit: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -51,7 +51,7 @@ public class Deposit: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.createdAt <- map["createdAt"] self.input <- map["in"] self.output <- map["out"] diff --git a/Source/Model/Reserve/DepositMovement.swift b/Source/Model/Reserve/DepositMovement.swift index f703e87..5f1662c 100644 --- a/Source/Model/Reserve/DepositMovement.swift +++ b/Source/Model/Reserve/DepositMovement.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// DepositMovement model. -public class DepositMovement: Mappable { +open class DepositMovement: Mappable { /// The amount of the deposit movement. public private(set) final var amount: String? @@ -28,7 +28,7 @@ public class DepositMovement: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -36,7 +36,7 @@ public class DepositMovement: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.amount <- map["amount"] self.currency <- map["currency"] } diff --git a/Source/Model/Reserve/ReserveStatistics.swift b/Source/Model/Reserve/ReserveStatistics.swift index bf6042d..e10d52c 100644 --- a/Source/Model/Reserve/ReserveStatistics.swift +++ b/Source/Model/Reserve/ReserveStatistics.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// ReserveStatistics model. -public class ReserveStatistics: Mappable { +open class ReserveStatistics: Mappable { /// The currency from the reserve. public private(set) final var currency: String? @@ -33,7 +33,7 @@ public class ReserveStatistics: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -41,7 +41,7 @@ public class ReserveStatistics: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.currency <- map["currency"] self.totals <- map["totals"] self.values <- map["values"] diff --git a/Source/Model/Reserve/Total.swift b/Source/Model/Reserve/Total.swift index be7f793..cc09d65 100644 --- a/Source/Model/Reserve/Total.swift +++ b/Source/Model/Reserve/Total.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Total model. -public class Total: Mappable { +open class Total: Mappable { /// The assets from the corresponding holding. public private(set) final var assets: String? @@ -38,7 +38,7 @@ public class Total: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -46,7 +46,7 @@ public class Total: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.assets <- map["assets"] self.commissions <- map["commissions"] self.liabilities <- map["liabilities"] diff --git a/Source/Model/Reserve/Value.swift b/Source/Model/Reserve/Value.swift index fc833ff..d5b04df 100644 --- a/Source/Model/Reserve/Value.swift +++ b/Source/Model/Reserve/Value.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Value model. -public class Value: Mappable { +open class Value: Mappable { /// The quantity of assets held for the corresponding holding, but converted to a different currency. public private(set) final var assets: String? @@ -38,7 +38,7 @@ public class Value: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -46,7 +46,7 @@ public class Value: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.assets <- map["assets"] self.currency <- map["currency"] self.liabilities <- map["liabilities"] diff --git a/Source/Model/Token.swift b/Source/Model/Token.swift index ac88724..1daf001 100644 --- a/Source/Model/Token.swift +++ b/Source/Model/Token.swift @@ -2,7 +2,7 @@ import Foundation import PromiseKit /// Token model. -public class Token: BaseModel { +open class Token: BaseModel { /// The bearer token. private(set) final var bearerToken: String? @@ -30,12 +30,12 @@ public class Token: BaseModel { - returns: A promise with the user. */ - public func getUser() -> Promise { + open func getUser() -> Promise { guard let _ = SessionManager.sharedInstance.getBearerToken() else { return Promise(error: AuthenticationRequiredError(message: "Missing bearer authorization")) } - return adapter.buildResponse(adapter.buildRequest(UserService.getUser())) + return adapter.buildResponse(request: adapter.buildRequest(request: UserService.getUser())) } } diff --git a/Source/Model/Transaction.swift b/Source/Model/Transaction.swift index d6815c0..6dfcc47 100644 --- a/Source/Model/Transaction.swift +++ b/Source/Model/Transaction.swift @@ -4,7 +4,7 @@ import ObjectMapper import SwiftClient /// Transaction model. -public class Transaction: BaseModel, Mappable { +open class Transaction: BaseModel, Mappable { /// The id of the transaction. public private(set) final var id: String? @@ -48,7 +48,7 @@ public class Transaction: BaseModel, Mappable { /// The card id path. private var cardIdPath: String? { get { - if let type = self.type where type.caseInsensitiveCompare("deposit") == .OrderedSame { + if let type = self.type, type.caseInsensitiveCompare("deposit") == .orderedSame { return destination?.cardId } @@ -96,7 +96,7 @@ public class Transaction: BaseModel, Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -104,7 +104,7 @@ public class Transaction: BaseModel, Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { id <- map["id"] createdAt <- map["createdAt"] denomination <- map["denomination"] @@ -125,12 +125,12 @@ public class Transaction: BaseModel, Mappable { - returns: A promise with the transaction. */ - public func cancel() -> Promise { + open func cancel() -> Promise { guard let id = self.id else { return Promise(error: UnexpectedResponseError(message: "Transaction id should not be nil.")) } - if (self.type?.caseInsensitiveCompare("deposit") == .OrderedSame) { + if (self.type?.caseInsensitiveCompare("deposit") == .orderedSame) { guard let _ = self.origin?.accountId else { return Promise(error: UnexpectedResponseError(message: "Origin accountId is missing from this transaction.")) } @@ -157,9 +157,9 @@ public class Transaction: BaseModel, Mappable { return Promise(error: LogicError(code: nil, message: "Unable to cancel uncommited transaction.")) case "waiting": - let request = self.adapter.buildRequest(UserCardService.cancelTransaction(cardIdPath, transactionId: id)) + let request = self.adapter.buildRequest(request: UserCardService.cancelTransaction(cardId: cardIdPath, transactionId: id)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) default: return Promise(error: LogicError(code: nil, message: String(format: "This transaction cannot be cancelled, because the current status is %@.", status))) @@ -171,8 +171,8 @@ public class Transaction: BaseModel, Mappable { - returns: A promise with the transaction. */ - public func commit() -> Promise { - return commit(nil, transactionCommit: nil) + open func commit() -> Promise { + return commit(otp: nil, transactionCommit: nil) } /** @@ -182,8 +182,8 @@ public class Transaction: BaseModel, Mappable { - returns: A promise with the transaction. */ - public func commit(otp: String) -> Promise { - return commit(otp, transactionCommit: nil) + open func commit(otp: String) -> Promise { + return commit(otp: otp, transactionCommit: nil) } /** @@ -193,8 +193,8 @@ public class Transaction: BaseModel, Mappable { - returns: A promise with the transaction. */ - public func commit(transactionCommit: TransactionCommitRequest) -> Promise { - return commit(nil, transactionCommit: nil) + open func commit(transactionCommit: TransactionCommitRequest) -> Promise { + return commit(otp: nil, transactionCommit: nil) } /** @@ -205,12 +205,12 @@ public class Transaction: BaseModel, Mappable { - returns: A promise with the transaction. */ - public func commit(otp: String?, transactionCommit: TransactionCommitRequest?) -> Promise { + open func commit(otp: String?, transactionCommit: TransactionCommitRequest?) -> Promise { guard let id = self.id else { return Promise(error: UnexpectedResponseError(message: "Transaction id should not be nil.")) } - if (self.type?.caseInsensitiveCompare("deposit") == .OrderedSame) { + if (self.type?.caseInsensitiveCompare("deposit") == .orderedSame) { guard let _ = self.origin?.accountId else { return Promise(error: UnexpectedResponseError(message: "Origin accountId is missing from this transaction.")) } @@ -238,14 +238,14 @@ public class Transaction: BaseModel, Mappable { let request: Request guard let transactionCommit = transactionCommit else { - request = self.adapter.buildRequest(UserCardService.confirmTransaction(cardIdPath, otp: otp, transactionId: id, transactionCommitRequest: nil)) + request = self.adapter.buildRequest(request: UserCardService.confirmTransaction(cardId: cardIdPath, otp: otp, transactionId: id, transactionCommitRequest: nil)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } - request = self.adapter.buildRequest(UserCardService.confirmTransaction(cardIdPath, otp: otp, transactionId: id, transactionCommitRequest: Mapper().toJSON(transactionCommit))) + request = self.adapter.buildRequest(request: UserCardService.confirmTransaction(cardId: cardIdPath, otp: otp, transactionId: id, transactionCommitRequest: Mapper().toJSON(transactionCommit))) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } } diff --git a/Source/Model/Transaction/Denomination.swift b/Source/Model/Transaction/Denomination.swift index 29ed883..310fe6c 100644 --- a/Source/Model/Transaction/Denomination.swift +++ b/Source/Model/Transaction/Denomination.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Denomination model. -public class Denomination: Mappable { +open class Denomination: Mappable { /// The amount of the transaction. public private(set) final var amount: String? @@ -38,7 +38,7 @@ public class Denomination: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -46,7 +46,7 @@ public class Denomination: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { amount <- map["amount"] currency <- map["currency"] pair <- map["pair"] diff --git a/Source/Model/Transaction/Destination.swift b/Source/Model/Transaction/Destination.swift index b9c7ccd..734d51f 100644 --- a/Source/Model/Transaction/Destination.swift +++ b/Source/Model/Transaction/Destination.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Destination model. -public class Destination: Mappable { +open class Destination: Mappable { /// The id of the account from the destination of the transaction. public private(set) final var accountId: String? @@ -83,7 +83,7 @@ public class Destination: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -91,7 +91,7 @@ public class Destination: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { accountId <- map["AccountId"] cardId <- map["CardId"] accountType <- map["accountType"] diff --git a/Source/Model/Transaction/Fee.swift b/Source/Model/Transaction/Fee.swift index 3ca2ab3..0635b75 100644 --- a/Source/Model/Transaction/Fee.swift +++ b/Source/Model/Transaction/Fee.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Fee model. -public class Fee: Mappable { +open class Fee: Mappable { /// The amount. public private(set) final var amount: String? @@ -41,7 +41,7 @@ public class Fee: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -49,7 +49,7 @@ public class Fee: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { amount <- map["amount"] currency <- map["currency"] percentage <- map["percentage"] diff --git a/Source/Model/Transaction/Merchant.swift b/Source/Model/Transaction/Merchant.swift index 61621d2..34ad1d9 100644 --- a/Source/Model/Transaction/Merchant.swift +++ b/Source/Model/Transaction/Merchant.swift @@ -43,7 +43,7 @@ public class Merchant: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** diff --git a/Source/Model/Transaction/NormalizedTransaction.swift b/Source/Model/Transaction/NormalizedTransaction.swift index ef4c43b..11bec40 100644 --- a/Source/Model/Transaction/NormalizedTransaction.swift +++ b/Source/Model/Transaction/NormalizedTransaction.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transaction normalized model. -public class NormalizedTransaction: Mappable { +open class NormalizedTransaction: Mappable { /// The amount of the transaction normalized. public private(set) final var amount: String? @@ -43,7 +43,7 @@ public class NormalizedTransaction: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -51,7 +51,7 @@ public class NormalizedTransaction: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.amount <- map["amount"] self.commission <- map["commission"] self.currency <- map["currency"] diff --git a/Source/Model/Transaction/Origin.swift b/Source/Model/Transaction/Origin.swift index 108d64c..238dffc 100644 --- a/Source/Model/Transaction/Origin.swift +++ b/Source/Model/Transaction/Origin.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Origin model. -public class Origin: Mappable { +open class Origin: Mappable { /// The id of the account from the origin of the transaction. public private(set) final var accountId: String? @@ -88,7 +88,7 @@ public class Origin: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -96,7 +96,7 @@ public class Origin: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { accountId <- map["AccountId"] cardId <- map["CardId"] accountType <- map["accountType"] diff --git a/Source/Model/Transaction/Parameters.swift b/Source/Model/Transaction/Parameters.swift index de4c6c3..dbcc8af 100644 --- a/Source/Model/Transaction/Parameters.swift +++ b/Source/Model/Transaction/Parameters.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Parameters model. -public class Parameters: Mappable { +open class Parameters: Mappable { /// The transaction currency. public private(set) final var currency: String? @@ -63,7 +63,7 @@ public class Parameters: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -71,7 +71,7 @@ public class Parameters: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { currency <- map["currency"] margin <- map["margin"] pair <- map["pair"] diff --git a/Source/Model/Transaction/Source.swift b/Source/Model/Transaction/Source.swift index 958da3c..457a187 100644 --- a/Source/Model/Transaction/Source.swift +++ b/Source/Model/Transaction/Source.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Source model. -public class Source: Mappable { +open class Source: Mappable { /// The id of the source. public private(set) final var id: String? @@ -28,7 +28,7 @@ public class Source: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -36,7 +36,7 @@ public class Source: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { id <- map["id"] amount <- map["amount"] } diff --git a/Source/Model/Transaction/TransactionCardDepositRequest.swift b/Source/Model/Transaction/TransactionCardDepositRequest.swift index 40acc9b..015dc9b 100644 --- a/Source/Model/Transaction/TransactionCardDepositRequest.swift +++ b/Source/Model/Transaction/TransactionCardDepositRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transaction card deposit request model. -public class TransactionCardDepositRequest: TransactionDepositRequest { +open class TransactionCardDepositRequest: TransactionDepositRequest { /// The card's security code. public private(set) final var securityCode: String? @@ -27,8 +27,8 @@ public class TransactionCardDepositRequest: TransactionDepositRequest { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { - super.init(map) + required public init?(map: Map) { + super.init(map: map) } /** @@ -36,8 +36,8 @@ public class TransactionCardDepositRequest: TransactionDepositRequest { - parameter map: The object to map. */ - public override func mapping(map: Map) { - super.mapping(map) + open override func mapping(map: Map) { + super.mapping(map: map) self.securityCode <- map["securityCode"] } diff --git a/Source/Model/Transaction/TransactionCommitRequest.swift b/Source/Model/Transaction/TransactionCommitRequest.swift index cfafa66..efe6628 100644 --- a/Source/Model/Transaction/TransactionCommitRequest.swift +++ b/Source/Model/Transaction/TransactionCommitRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transaction commit request model. -public class TransactionCommitRequest: Mappable { +open class TransactionCommitRequest: Mappable { /// The transaction message. public private(set) final var message: String? @@ -37,7 +37,7 @@ public class TransactionCommitRequest: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -45,7 +45,7 @@ public class TransactionCommitRequest: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.message <- map["message"] self.securityCode <- map["securityCode"] } diff --git a/Source/Model/Transaction/TransactionDenominationRequest.swift b/Source/Model/Transaction/TransactionDenominationRequest.swift index 5a4eabc..4494615 100644 --- a/Source/Model/Transaction/TransactionDenominationRequest.swift +++ b/Source/Model/Transaction/TransactionDenominationRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transaction denomination request model. -public class TransactionDenominationRequest: Mappable { +open class TransactionDenominationRequest: Mappable { /// The amount of the transaction request. public private(set) final var amount: String? @@ -28,7 +28,7 @@ public class TransactionDenominationRequest: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -36,7 +36,7 @@ public class TransactionDenominationRequest: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.amount <- map["amount"] self.currency <- map["currency"] } diff --git a/Source/Model/Transaction/TransactionDepositRequest.swift b/Source/Model/Transaction/TransactionDepositRequest.swift index f7b4f5a..d31e2c1 100644 --- a/Source/Model/Transaction/TransactionDepositRequest.swift +++ b/Source/Model/Transaction/TransactionDepositRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transaction deposit request model. -public class TransactionDepositRequest: TransactionRequest { +open class TransactionDepositRequest: TransactionRequest { /// The origin of the transaction request in case of a deposit. public private(set) final var origin: String? @@ -26,8 +26,8 @@ public class TransactionDepositRequest: TransactionRequest { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { - super.init(map) + required public init?(map: Map) { + super.init(map: map) } /** @@ -35,8 +35,8 @@ public class TransactionDepositRequest: TransactionRequest { - parameter map: The object to map. */ - public override func mapping(map: Map) { - super.mapping(map) + open override func mapping(map: Map) { + super.mapping(map: map) self.origin <- map["origin"] } diff --git a/Source/Model/Transaction/TransactionRequest.swift b/Source/Model/Transaction/TransactionRequest.swift index baf59ba..b60a27c 100644 --- a/Source/Model/Transaction/TransactionRequest.swift +++ b/Source/Model/Transaction/TransactionRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transaction request model. -public class TransactionRequest: Mappable { +open class TransactionRequest: Mappable { /// The denomination of the transaction request. public private(set) final var denomination: TransactionDenominationRequest? @@ -23,7 +23,7 @@ public class TransactionRequest: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class TransactionRequest: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.denomination <- map["denomination"] } diff --git a/Source/Model/Transaction/TransactionTransferRequest.swift b/Source/Model/Transaction/TransactionTransferRequest.swift index 916e974..01fedbf 100644 --- a/Source/Model/Transaction/TransactionTransferRequest.swift +++ b/Source/Model/Transaction/TransactionTransferRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transaction destination request model. -public class TransactionTransferRequest: TransactionRequest { +open class TransactionTransferRequest: TransactionRequest { /// The destination of the transaction request. public private(set) final var destination: String? @@ -26,8 +26,8 @@ public class TransactionTransferRequest: TransactionRequest { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { - super.init(map) + required public init?(map: Map) { + super.init(map: map) } /** @@ -35,8 +35,8 @@ public class TransactionTransferRequest: TransactionRequest { - parameter map: The object to map. */ - public override func mapping(map: Map) { - super.mapping(map) + open override func mapping(map: Map) { + super.mapping(map: map) self.destination <- map["destination"] } diff --git a/Source/Model/User.swift b/Source/Model/User.swift index 5717fbd..75b8508 100644 --- a/Source/Model/User.swift +++ b/Source/Model/User.swift @@ -4,7 +4,7 @@ import PromiseKit import SwiftClient /// User model. -public class User: BaseModel, Mappable { +open class User: BaseModel, Mappable { /// The user country. public private(set) final var country: String? @@ -75,7 +75,7 @@ public class User: BaseModel, Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -83,7 +83,7 @@ public class User: BaseModel, Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.country <- map["country"] self.currencies <- map["currencies"] self.email <- map["email"] @@ -104,10 +104,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the created card. */ - public func createCard(cardRequest: CardRequest) -> Promise { - let request = self.adapter.buildRequest(UserCardService.createUserCard(Mapper().toJSON(cardRequest))) + open func createCard(cardRequest: CardRequest) -> Promise { + let request = self.adapter.buildRequest(request: UserCardService.createUserCard(cardRequest: Mapper().toJSON(cardRequest))) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -117,10 +117,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the created contact. */ - public func createContact(contactRequest: ContactRequest) -> Promise { - let request = self.adapter.buildRequest(UserService.createContact(Mapper().toJSON(contactRequest))) + open func createContact(contactRequest: ContactRequest) -> Promise { + let request = self.adapter.buildRequest(request: UserService.createContact(contactRequest: Mapper().toJSON(contactRequest))) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -131,9 +131,9 @@ public class User: BaseModel, Mappable { - returns: A promise with the created document. */ public func createDocument(document: Document) -> Promise { - let request = self.adapter.buildRequest(UserService.createDocument(Mapper().toJSON(document))) + let request = self.adapter.buildRequest(request: UserService.createDocument(document: document)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -141,10 +141,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the user accounts list. */ - public func getAccounts() -> Promise<[Account]> { - let request = self.adapter.buildRequest(AccountsService.getUserAccounts()) + open func getAccounts() -> Promise<[Account]> { + let request = self.adapter.buildRequest(request: AccountsService.getUserAccounts()) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -154,10 +154,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the user account. */ - public func getAccountById(accountId: String) -> Promise { - let request = self.adapter.buildRequest(AccountsService.getUserAccountById(accountId)) + open func getAccountById(accountId: String) -> Promise { + let request = self.adapter.buildRequest(request: AccountsService.getUserAccountById(accountId: accountId)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -165,9 +165,9 @@ public class User: BaseModel, Mappable { - returns: A promise with the user balance. */ - public func getBalances() -> Promise<[Currency]> { - let request = self.adapter.buildRequest(UserService.getUserBalances()) - let balance: Promise = self.adapter.buildResponse(request) + open func getBalances() -> Promise<[Currency]> { + let request = self.adapter.buildRequest(request: UserService.getUserBalances()) + let balance: Promise = self.adapter.buildResponse(request: request) return balance.then { (balance: Balance) -> Promise<[Currency]> in return Promise { fulfill, reject in @@ -185,7 +185,7 @@ public class User: BaseModel, Mappable { return } - currencies.sort({$0.0 < $1.0}).forEach({ (currency: (String, Currency)) -> () in + currencies.sorted(by: {$0.0 < $1.0}).forEach({ (currency: (String, Currency)) -> Void in responseCurrencies.append(currency.1) }) @@ -201,9 +201,9 @@ public class User: BaseModel, Mappable { - returns: A promise with the user balance for the currency. */ - public func getBalanceByCurrency(currency: String) -> Promise { - let request = self.adapter.buildRequest(UserService.getUserBalances()) - let balance: Promise = self.adapter.buildResponse(request) + open func getBalanceByCurrency(currency: String) -> Promise { + let request = self.adapter.buildRequest(request: UserService.getUserBalances()) + let balance: Promise = self.adapter.buildResponse(request: request) return balance.then { (balance: Balance) -> Promise in return Promise { fulfill, reject in @@ -235,10 +235,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the cards user list. */ - public func getCards() -> Promise<[Card]> { - let request = self.adapter.buildRequest(UserCardService.getUserCards()) + open func getCards() -> Promise<[Card]> { + let request = self.adapter.buildRequest(request: UserCardService.getUserCards()) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -248,10 +248,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the card. */ - public func getCardById(cardId: String) -> Promise { - let request = self.adapter.buildRequest(UserCardService.getUserCardById(cardId)) + open func getCardById(cardId: String) -> Promise { + let request = self.adapter.buildRequest(request: UserCardService.getUserCardById(cardId: cardId)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -261,13 +261,13 @@ public class User: BaseModel, Mappable { - returns: A promise with the list of cards. */ - public func getCardsByCurrency(currency: String) -> Promise<[Card]> { - let request = self.adapter.buildRequest(UserCardService.getUserCards()) - let cards: Promise<[Card]> = self.adapter.buildResponse(request) + open func getCardsByCurrency(currency: String) -> Promise<[Card]> { + let request = self.adapter.buildRequest(request: UserCardService.getUserCards()) + let cards: Promise<[Card]> = self.adapter.buildResponse(request: request) return cards.then { (cards: [Card]) -> Promise<[Card]> in return Promise { fulfill, reject in - let filteredCards = cards.filter() { + let filteredCards = cards.filter { $0.currency == currency } @@ -285,10 +285,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the list of user contacts. */ - public func getContacts() -> Promise<[Contact]> { - let request = self.adapter.buildRequest(UserService.getUserContacts()) + open func getContacts() -> Promise<[Contact]> { + let request = self.adapter.buildRequest(request: UserService.getUserContacts()) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -297,9 +297,9 @@ public class User: BaseModel, Mappable { - returns: A promise with the list of user documents. */ public func getDocuments() -> Promise<[Document]> { - let request = self.adapter.buildRequest(UserService.getUserDocuments()) + let request = self.adapter.buildRequest(request: UserService.getUserDocuments()) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -307,10 +307,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the list of user phones. */ - public func getPhones() -> Promise<[Phone]> { - let request = self.adapter.buildRequest(UserService.getUserPhones()) + open func getPhones() -> Promise<[Phone]> { + let request = self.adapter.buildRequest(request: UserService.getUserPhones()) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } /** @@ -318,9 +318,9 @@ public class User: BaseModel, Mappable { - returns: A promise with the user balance. */ - public func getTotalBalances() -> Promise { - let request = self.adapter.buildRequest(UserService.getUserBalances()) - let balance: Promise = self.adapter.buildResponse(request) + open func getTotalBalances() -> Promise { + let request = self.adapter.buildRequest(request: UserService.getUserBalances()) + let balance: Promise = self.adapter.buildResponse(request: request) return balance.then { (balance: Balance) -> Promise in return Promise { fulfill, reject in @@ -340,13 +340,13 @@ public class User: BaseModel, Mappable { - returns: A paginator with the user transactions. */ - public func getUserTransactions() -> Paginator { - let request = self.adapter.buildRequest(UserService.getUserTransactions(Header.buildRangeHeader(Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) + open func getUserTransactions() -> Paginator { + let request = self.adapter.buildRequest(request: UserService.getUserTransactions(range: Header.buildRangeHeader(start: Paginator.DEFAULT_START, end: Paginator.DEFAULT_OFFSET - 1))) let paginator: Paginator = Paginator(countClosure: { () -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(UserService.getUserTransactions(Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: UserService.getUserTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Range header should not be nil.")) return @@ -356,11 +356,11 @@ public class User: BaseModel, Mappable { }) } }, - elements: self.adapter.buildResponse(request), + elements: self.adapter.buildResponse(request: request), hasNextPageClosure: { (currentPage) -> Promise in return Promise { fulfill, reject in - self.adapter.buildRequest(UserService.getUserTransactions(Header.buildRangeHeader(0, end: 1))).end({ (response: Response) -> Void in - guard let count = Header.getTotalNumberOfResults(response.headers) else { + self.adapter.buildRequest(request: UserService.getUserTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in + guard let count = Header.getTotalNumberOfResults(headers: response.headers) else { reject(UnexpectedResponseError(message: "Content-Range header should not be nil.")) return @@ -371,8 +371,8 @@ public class User: BaseModel, Mappable { } }, nextPageClosure: { (range) -> Promise<[Transaction]> in - let request = self.adapter.buildRequest(UserService.getUserTransactions(range)) - let promise: Promise<[Transaction]> = self.adapter.buildResponse(request) + let request = self.adapter.buildRequest(request: UserService.getUserTransactions(range: range)) + let promise: Promise<[Transaction]> = self.adapter.buildResponse(request: request) return promise }) @@ -387,10 +387,10 @@ public class User: BaseModel, Mappable { - returns: A promise with the updated user. */ - public func update(updateFields: [String: AnyObject]) -> Promise { - let request = self.adapter.buildRequest(UserService.updateUser(updateFields)) + open func update(updateFields: [String: Any]) -> Promise { + let request = self.adapter.buildRequest(request: UserService.updateUser(updatefields: updateFields)) - return self.adapter.buildResponse(request) + return self.adapter.buildResponse(request: request) } } diff --git a/Source/Model/User/Contact.swift b/Source/Model/User/Contact.swift index 92de855..06ccd2d 100644 --- a/Source/Model/User/Contact.swift +++ b/Source/Model/User/Contact.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Contact model. -public class Contact: Mappable { +open class Contact: Mappable { /// The contact id. public private(set) final var id: String? @@ -53,7 +53,7 @@ public class Contact: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -61,7 +61,7 @@ public class Contact: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.id <- map["id"] self.addresses <- map["addresses"] self.company <- map["company"] diff --git a/Source/Model/User/ContactRequest.swift b/Source/Model/User/ContactRequest.swift index f878419..83efc15 100644 --- a/Source/Model/User/ContactRequest.swift +++ b/Source/Model/User/ContactRequest.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// ContactRequest model. -public class ContactRequest: Mappable { +open class ContactRequest: Mappable { /// The list of addresses. public private(set) final var addresses: [String]? @@ -43,7 +43,7 @@ public class ContactRequest: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -51,7 +51,7 @@ public class ContactRequest: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.addresses <- map["addresses"] self.company <- map["company"] self.emails <- map["emails"] diff --git a/Source/Model/User/InternationalizationUserSetting.swift b/Source/Model/User/InternationalizationUserSetting.swift index abbd199..decea25 100644 --- a/Source/Model/User/InternationalizationUserSetting.swift +++ b/Source/Model/User/InternationalizationUserSetting.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// InternationalizationUserSetting model. -public class InternationalizationUserSetting: Mappable { +open class InternationalizationUserSetting: Mappable { /// The locale for the setting. public private(set) final var locale: String? @@ -23,7 +23,7 @@ public class InternationalizationUserSetting: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class InternationalizationUserSetting: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { locale <- map["locale"] } diff --git a/Source/Model/User/InternationalizationUserSettings.swift b/Source/Model/User/InternationalizationUserSettings.swift index 1c57ae8..0e99de2 100644 --- a/Source/Model/User/InternationalizationUserSettings.swift +++ b/Source/Model/User/InternationalizationUserSettings.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// InternationalizationUserSettings model. -public class InternationalizationUserSettings: Mappable { +open class InternationalizationUserSettings: Mappable { /// The internationalization language user settings. public private(set) final var language: InternationalizationUserSetting? @@ -33,7 +33,7 @@ public class InternationalizationUserSettings: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -41,7 +41,7 @@ public class InternationalizationUserSettings: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { language <- map["language"] dateTimeFormat <- map["dateTimeFormat"] numberFormat <- map["numberFormat"] diff --git a/Source/Model/User/Phone.swift b/Source/Model/User/Phone.swift index 8c1ee81..e6cc2bb 100644 --- a/Source/Model/User/Phone.swift +++ b/Source/Model/User/Phone.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Phone model. -public class Phone: Mappable { +open class Phone: Mappable { /// The contact id. public private(set) final var id: String? @@ -38,7 +38,7 @@ public class Phone: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -46,7 +46,7 @@ public class Phone: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.id <- map["id"] self.e164Masked <- map["e164Masked"] self.primary <- map["primary"] diff --git a/Source/Model/User/Settings/Otp.swift b/Source/Model/User/Settings/Otp.swift index 3b998af..a610bc2 100644 --- a/Source/Model/User/Settings/Otp.swift +++ b/Source/Model/User/Settings/Otp.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Otp settings model. -public class Otp: Mappable { +open class Otp: Mappable { /// The login otp settings. public private(set) final var login: Login? @@ -28,7 +28,7 @@ public class Otp: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -36,7 +36,7 @@ public class Otp: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.login <- map["login"] self.transactions <- map["transactions"] } diff --git a/Source/Model/User/Settings/Otp/Login.swift b/Source/Model/User/Settings/Otp/Login.swift index d5f4e3a..fec75bb 100644 --- a/Source/Model/User/Settings/Otp/Login.swift +++ b/Source/Model/User/Settings/Otp/Login.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Login otp settings model. -public class Login: Mappable { +open class Login: Mappable { /// A boolean indicating if the otp is enable for the login process. public private(set) final var enabled: Bool? @@ -23,7 +23,7 @@ public class Login: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class Login: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.enabled <- map["enabled"] } diff --git a/Source/Model/User/Settings/Otp/Transactions.swift b/Source/Model/User/Settings/Otp/Transactions.swift index 3a25de7..a3cd5c8 100644 --- a/Source/Model/User/Settings/Otp/Transactions.swift +++ b/Source/Model/User/Settings/Otp/Transactions.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transactions otp settings model. -public class Transactions: Mappable { +open class Transactions: Mappable { /// The send transactions otp settings. public private(set) final var send: Send? @@ -33,7 +33,7 @@ public class Transactions: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -41,7 +41,7 @@ public class Transactions: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.send <- map["send"] self.transfer <- map["transfer"] self.withdraw <- map["withdraw"] diff --git a/Source/Model/User/Settings/Otp/Transactions/Send.swift b/Source/Model/User/Settings/Otp/Transactions/Send.swift index d65d489..b7db566 100644 --- a/Source/Model/User/Settings/Otp/Transactions/Send.swift +++ b/Source/Model/User/Settings/Otp/Transactions/Send.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Send otp settings model. -public class Send: Mappable { +open class Send: Mappable { /// A boolean indicating if the otp is enable for the transactions send process. public private(set) final var enabled: Bool? @@ -23,7 +23,7 @@ public class Send: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class Send: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.enabled <- map["enabled"] } diff --git a/Source/Model/User/Settings/Otp/Transactions/Transfer.swift b/Source/Model/User/Settings/Otp/Transactions/Transfer.swift index 65935f0..d847eba 100644 --- a/Source/Model/User/Settings/Otp/Transactions/Transfer.swift +++ b/Source/Model/User/Settings/Otp/Transactions/Transfer.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Transfer otp settings model. -public class Transfer: Mappable { +open class Transfer: Mappable { /// A boolean indicating if the otp is enable for the transactions transfer process. public private(set) final var enabled: Bool? @@ -23,7 +23,7 @@ public class Transfer: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class Transfer: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.enabled <- map["enabled"] } diff --git a/Source/Model/User/Settings/Otp/Transactions/Withdraw.swift b/Source/Model/User/Settings/Otp/Transactions/Withdraw.swift index 59e39e1..bcf1ec2 100644 --- a/Source/Model/User/Settings/Otp/Transactions/Withdraw.swift +++ b/Source/Model/User/Settings/Otp/Transactions/Withdraw.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Withdraw otp settings model. -public class Withdraw: Mappable { +open class Withdraw: Mappable { /// The transactions withdraw crypto otp settings. public private(set) final var crypto: Crypto? @@ -23,7 +23,7 @@ public class Withdraw: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class Withdraw: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.crypto <- map["crypto"] } diff --git a/Source/Model/User/Settings/Otp/Transactions/Withdraw/Crypto.swift b/Source/Model/User/Settings/Otp/Transactions/Withdraw/Crypto.swift index bde7d70..6bcb649 100644 --- a/Source/Model/User/Settings/Otp/Transactions/Withdraw/Crypto.swift +++ b/Source/Model/User/Settings/Otp/Transactions/Withdraw/Crypto.swift @@ -2,7 +2,7 @@ import Foundation import ObjectMapper /// Withdraw crypto otp settings model. -public class Crypto: Mappable { +open class Crypto: Mappable { /// A boolean indicating if the otp is enable for the transactions withdraw process. public private(set) final var enabled: Bool? @@ -23,7 +23,7 @@ public class Crypto: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -31,7 +31,7 @@ public class Crypto: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { self.enabled <- map["enabled"] } diff --git a/Source/Model/User/UserSettings.swift b/Source/Model/User/UserSettings.swift index 8348973..6fb6203 100644 --- a/Source/Model/User/UserSettings.swift +++ b/Source/Model/User/UserSettings.swift @@ -2,13 +2,13 @@ import Foundation import ObjectMapper /// UserSettings model. -public class UserSettings: Mappable { +open class UserSettings: Mappable { /// The user's default currency. - public private(set) var currency: String? + open private(set) var currency: String? /// A boolean indicating if the user has the news subscription enabled. - public private(set) var hasNewsSubscription: Bool? + open private(set) var hasNewsSubscription: Bool? /// The user internationalization settings. public private(set) final var intl: InternationalizationUserSettings? @@ -43,7 +43,7 @@ public class UserSettings: Mappable { - parameter map: Mapping data object. */ - required public init?(_ map: Map) { + required public init?(map: Map) { } /** @@ -51,7 +51,7 @@ public class UserSettings: Mappable { - parameter map: The object to map. */ - public func mapping(map: Map) { + open func mapping(map: Map) { currency <- map["currency"] hasNewsSubscription <- map["hasNewsSubscription"] intl <- map["intl"] diff --git a/Source/Paginator/Paginator.swift b/Source/Paginator/Paginator.swift index 4624e45..ec45c83 100644 --- a/Source/Paginator/Paginator.swift +++ b/Source/Paginator/Paginator.swift @@ -3,7 +3,7 @@ import ObjectMapper import PromiseKit /// Paginator model. -public class Paginator: PaginatorProtocol { +open class Paginator: PaginatorProtocol { /// Default offset page. static var DEFAULT_OFFSET: Int { @@ -19,16 +19,16 @@ public class Paginator: PaginatorProtocol { private var currentPage: Int /// A promise with the first list of elements. - public let elements: Promise<[T]> + open let elements: Promise<[T]> /// Closure to get a promise with the total number of elements. let countClosure: () -> Promise /// Closure to get a promise with a bolean indicating if exists a next page of elements. - let hasNextPageClosure: (currentPage: Int) -> Promise + let hasNextPageClosure: (_ currentPage: Int) -> Promise /// Closure to get a promise with the next page of elements. - let nextPageClosure: (range: String) -> Promise<[T]> + let nextPageClosure: (_ range: String) -> Promise<[T]> /** Constructor @@ -38,7 +38,7 @@ public class Paginator: PaginatorProtocol { - parameter hasNextPageClosure: A closure to check if there are more pages. - parameter nextPageClosure: A closure to get the next page of elements. */ - init(countClosure: () -> Promise, elements: Promise<[T]>, hasNextPageClosure: (currentPage: Int) -> Promise, nextPageClosure: (range: String) -> Promise<[T]>) { + init(countClosure: @escaping () -> Promise, elements: Promise<[T]>, hasNextPageClosure: @escaping (_ currentPage: Int) -> Promise, nextPageClosure: @escaping (_ range: String) -> Promise<[T]>) { self.countClosure = countClosure self.currentPage = 1 self.elements = elements @@ -51,7 +51,7 @@ public class Paginator: PaginatorProtocol { - returns: A promise with the total number of elements. */ - public func count() -> Promise { + open func count() -> Promise { return countClosure() } @@ -60,7 +60,7 @@ public class Paginator: PaginatorProtocol { - returns: A promise with the array of elements. */ - public func getNext() -> Promise<[T]> { + open func getNext() -> Promise<[T]> { defer { currentPage += 1 @@ -69,7 +69,7 @@ public class Paginator: PaginatorProtocol { objc_sync_enter(self.currentPage) - let promise: Promise<[T]> = self.nextPageClosure(range: Header.buildRangeHeader((Paginator.DEFAULT_OFFSET * currentPage), end: ((Paginator.DEFAULT_OFFSET * currentPage) + Paginator.DEFAULT_OFFSET) - 1)) + let promise: Promise<[T]> = self.nextPageClosure(Header.buildRangeHeader(start: (Paginator.DEFAULT_OFFSET * currentPage), end: ((Paginator.DEFAULT_OFFSET * currentPage) + Paginator.DEFAULT_OFFSET) - 1)) return promise } @@ -79,8 +79,8 @@ public class Paginator: PaginatorProtocol { - returns: A promise with the bolean indicator. */ - public func hasNext() -> Promise { - return self.hasNextPageClosure(currentPage: self.currentPage) + open func hasNext() -> Promise { + return self.hasNextPageClosure(self.currentPage) } } diff --git a/Source/Paginator/PaginatorProtocol.swift b/Source/Paginator/PaginatorProtocol.swift index 07e0454..8308d20 100644 --- a/Source/Paginator/PaginatorProtocol.swift +++ b/Source/Paginator/PaginatorProtocol.swift @@ -6,7 +6,7 @@ import PromiseKit protocol PaginatorProtocol { /// Paginator generic type. - associatedtype T + associatedtype PaginatorType /** A closure to get a promise with the total number of elements. @@ -20,13 +20,13 @@ protocol PaginatorProtocol { - returns: A promise with the array of elements. */ - var nextPageClosure: (range: String) -> Promise<[T]> {get} + var nextPageClosure: (_ range: String) -> Promise<[PaginatorType]> {get} /** A closure to get a promise with a bolean indicating if exists a next page of elements. - returns: A promise with the bolean indicator. */ - var hasNextPageClosure: (currentPage: Int) -> Promise {get} + var hasNextPageClosure: (_ currentPage: Int) -> Promise {get} } diff --git a/Source/Service/AccountsService.swift b/Source/Service/AccountsService.swift index c38871d..c6cdabe 100644 --- a/Source/Service/AccountsService.swift +++ b/Source/Service/AccountsService.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// Accounts service. -public class AccountsService { +open class AccountsService { /** Gets an user account. @@ -12,7 +12,7 @@ public class AccountsService { - returns: A request to get an user account. */ static func getUserAccountById(accountId: String) -> Request { - return UpholdClient().get(String(format: "/v0/me/accounts/%@", accountId)) + return UpholdClient().get(url: String(format: "/v0/me/accounts/%@", accountId)) } /** @@ -21,7 +21,7 @@ public class AccountsService { - returns: A request to get the user accounts. */ static func getUserAccounts() -> Request { - return UpholdClient().get("/v0/me/accounts") + return UpholdClient().get(url: "/v0/me/accounts") } } diff --git a/Source/Service/OAuth2Service.swift b/Source/Service/OAuth2Service.swift index df63041..e055c3f 100644 --- a/Source/Service/OAuth2Service.swift +++ b/Source/Service/OAuth2Service.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// OAuth2 service. -public class OAuth2Service { +open class OAuth2Service { /** Performs a request to get a user access token. @@ -15,7 +15,7 @@ public class OAuth2Service { - returns: A request to get the bearer token. */ static func requestToken(clientId: String, clientSecret: String, code: String, grantType: String) -> Request { - return UpholdClient().post("/oauth2/token").auth(clientId, clientSecret).send(String(format: "code=%@", code)).send(String(format: "grant_type=%@", grantType)) + return UpholdClient().post(url: "/oauth2/token").auth(username: clientId, password: clientSecret).send(data: String(format: "code=%@", code)).send(data: String(format: "grant_type=%@", grantType)) } } diff --git a/Source/Service/ReserveService.swift b/Source/Service/ReserveService.swift index 430ad55..b4d5a95 100644 --- a/Source/Service/ReserveService.swift +++ b/Source/Service/ReserveService.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// Reserve service. -public class ReserveService { +open class ReserveService { /** Creates a request to get the reserve ledger. @@ -12,7 +12,7 @@ public class ReserveService { - returns: A request to get the reserve ledger. */ static func getLedger(range: String) -> Request { - return UpholdClient().get("/v0/reserve/ledger").set("Range", range) + return UpholdClient().get(url: "/v0/reserve/ledger").set(key: "Range", value: range) } /** @@ -23,7 +23,7 @@ public class ReserveService { - returns: A request to get a reserve transaction. */ static func getReserveTransactionById(transactionId: String) -> Request { - return UpholdClient().get(String(format: "/v0/reserve/transactions/%@", transactionId)) + return UpholdClient().get(url: String(format: "/v0/reserve/transactions/%@", transactionId)) } /** @@ -34,7 +34,7 @@ public class ReserveService { - returns: A request to get the reserve transactions. */ static func getReserveTransactions(range: String) -> Request { - return UpholdClient().get("/v0/reserve/transactions").set("Range", range) + return UpholdClient().get(url: "/v0/reserve/transactions").set(key: "Range", value: range) } /** @@ -43,7 +43,7 @@ public class ReserveService { - returns: A request to get the reserve statistics. */ static func getStatistics() -> Request { - return UpholdClient().get("/v0/reserve/statistics") + return UpholdClient().get(url: "/v0/reserve/statistics") } } diff --git a/Source/Service/TickerService.swift b/Source/Service/TickerService.swift index 1eac835..73c28cb 100644 --- a/Source/Service/TickerService.swift +++ b/Source/Service/TickerService.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// Ticker service. -public class TickerService { +open class TickerService { /** Creates a request to get the tickers on the system. @@ -10,7 +10,7 @@ public class TickerService { - returns: A request to get the tickers on the system. */ static func getAllTickers() -> Request { - return UpholdClient().get("/v0/ticker") + return UpholdClient().get(url: "/v0/ticker") } /** @@ -21,7 +21,7 @@ public class TickerService { - returns: A request to get the tickers on the system for the selected currency. */ static func getAllTickersByCurrency(currency: String) -> Request { - return UpholdClient().get(String(format: "/v0/ticker/%@", currency)) + return UpholdClient().get(url: String(format: "/v0/ticker/%@", currency)) } } diff --git a/Source/Service/UserCardService.swift b/Source/Service/UserCardService.swift index 653be38..758b361 100644 --- a/Source/Service/UserCardService.swift +++ b/Source/Service/UserCardService.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// UserCard service. -public class UserCardService { +open class UserCardService { /** Creates a request to cancel a transaction. @@ -13,7 +13,7 @@ public class UserCardService { - returns: A request to cancel the transaction. */ static func cancelTransaction(cardId: String, transactionId: String) -> Request { - return UpholdClient().post(String(format: "/v0/me/cards/%@/transactions/%@/cancel", cardId, transactionId)) + return UpholdClient().post(url: String(format: "/v0/me/cards/%@/transactions/%@/cancel", cardId, transactionId)) } /** @@ -24,8 +24,8 @@ public class UserCardService { - returns: A request to create a card. */ - static func createCardAddress(cardId: String, addressRequest: AnyObject) -> Request { - return UpholdClient().post(String(format: "/v0/me/cards/%@/addresses", cardId)).send(addressRequest) + static func createCardAddress(cardId: String, addressRequest: Any) -> Request { + return UpholdClient().post(url: String(format: "/v0/me/cards/%@/addresses", cardId)).send(data: addressRequest) } /** @@ -38,20 +38,20 @@ public class UserCardService { - returns: A request to confirm the transaction. */ - static func confirmTransaction(cardId: String, otp: String?, transactionId: String, transactionCommitRequest: AnyObject?) -> Request { - let request = UpholdClient().post(String(format: "/v0/me/cards/%@/transactions/%@/commit", cardId, transactionId)) + static func confirmTransaction(cardId: String, otp: String?, transactionId: String, transactionCommitRequest: Any?) -> Request { + let request = UpholdClient().post(url: String(format: "/v0/me/cards/%@/transactions/%@/commit", cardId, transactionId)) - guard let guardedOtp = otp, guardedTransactionCommitRequest = transactionCommitRequest else { + guard let guardedOtp = otp, let guardedTransactionCommitRequest = transactionCommitRequest else { if let otp = otp { - return request.set("OTP-Token", otp) + return request.set(key: "OTP-Token", value: otp) } else if let transactionCommitRequest = transactionCommitRequest { - return request.send(transactionCommitRequest) + return request.send(data: transactionCommitRequest) } return request } - return request.set("OTP-Token", guardedOtp).send(guardedTransactionCommitRequest) + return request.set(key: "OTP-Token", value: guardedOtp).send(data: guardedTransactionCommitRequest) } /** @@ -63,8 +63,8 @@ public class UserCardService { - returns: A request to create a transaction. */ - static func createTransaction(cardId: String, commit: Bool, transactionRequest: AnyObject) -> Request { - return UpholdClient().post(String(format: "/v0/me/cards/%@/transactions", cardId)).query(["commit": commit ? "true" : "false"]).send(transactionRequest) + static func createTransaction(cardId: String, commit: Bool, transactionRequest: Any) -> Request { + return UpholdClient().post(url: String(format: "/v0/me/cards/%@/transactions", cardId)).query(query: ["commit": commit ? "true" : "false"]).send(data: transactionRequest) } /** @@ -74,8 +74,8 @@ public class UserCardService { - returns: A request to create a card. */ - static func createUserCard(cardRequest: AnyObject) -> Request { - return UpholdClient().post("/v0/me/cards").send(cardRequest) + static func createUserCard(cardRequest: Any) -> Request { + return UpholdClient().post(url: "/v0/me/cards").send(data: cardRequest) } /** @@ -86,7 +86,7 @@ public class UserCardService { - returns: A request to create a transaction. */ static func getUserCardById(cardId: String) -> Request { - return UpholdClient().get(String(format: "/v0/me/cards/%@", cardId)) + return UpholdClient().get(url: String(format: "/v0/me/cards/%@", cardId)) } /** @@ -95,7 +95,7 @@ public class UserCardService { - returns: A request to get the user cards. */ static func getUserCards() -> Request { - return UpholdClient().get("/v0/me/cards") + return UpholdClient().get(url: "/v0/me/cards") } /** @@ -107,7 +107,7 @@ public class UserCardService { - returns: A request to get the list of transactions for a card. */ static func getUserCardTransactions(cardId: String, range: String) -> Request { - return UpholdClient().get(String(format: "/v0/me/cards/%@/transactions", cardId)).set("Range", range) + return UpholdClient().get(url: String(format: "/v0/me/cards/%@/transactions", cardId)).set(key: "Range", value: range) } /** @@ -118,8 +118,8 @@ public class UserCardService { - returns: A request to update a card. */ - static func updateCard(cardId: String, updateFields: AnyObject) -> Request { - return UpholdClient().patch(String(format: "/v0/me/cards/%@", cardId)).send(updateFields) + static func updateCard(cardId: String, updateFields: Any) -> Request { + return UpholdClient().patch(url: String(format: "/v0/me/cards/%@", cardId)).send(data: updateFields) } } diff --git a/Source/Service/UserService.swift b/Source/Service/UserService.swift index 58f95b3..90dfe96 100644 --- a/Source/Service/UserService.swift +++ b/Source/Service/UserService.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// User service. -public class UserService { +open class UserService { /** Creates a request to create a contact. @@ -11,8 +11,8 @@ public class UserService { - returns: A request to create a contact. */ - static func createContact(contactRequest: AnyObject) -> Request { - return UpholdClient().post("/v0/me/contacts").send(contactRequest) + static func createContact(contactRequest: Any) -> Request { + return UpholdClient().post(url: "/v0/me/contacts").send(data: contactRequest) } /** @@ -23,7 +23,7 @@ public class UserService { - returns: A request to create a document. */ static func createDocument(document: AnyObject) -> Request { - return UpholdClient().post("/v0/me/documents").send(document) + return UpholdClient().post(url: "/v0/me/documents").send(data: document) } /** @@ -32,7 +32,7 @@ public class UserService { - returns: A request to get the user information. */ static func getUser() -> Request { - return UpholdClient().get("/v0/me") + return UpholdClient().get(url: "/v0/me") } /** @@ -41,7 +41,7 @@ public class UserService { - returns: A request to get the user balances. */ static func getUserBalances() -> Request { - return UpholdClient().get("/v0/me") + return UpholdClient().get(url: "/v0/me") } /** @@ -50,7 +50,7 @@ public class UserService { - returns: A request to get the user contacts. */ static func getUserContacts() -> Request { - return UpholdClient().get("/v0/me/contacts") + return UpholdClient().get(url: "/v0/me/contacts") } /** @@ -59,7 +59,7 @@ public class UserService { - returns: A request to get the user documents. */ static func getUserDocuments() -> Request { - return UpholdClient().get("/v0/me/documents") + return UpholdClient().get(url: "/v0/me/documents") } /** @@ -68,7 +68,7 @@ public class UserService { - returns: A request to get the user phones. */ static func getUserPhones() -> Request { - return UpholdClient().get("/v0/me/phones") + return UpholdClient().get(url: "/v0/me/phones") } /** @@ -79,7 +79,7 @@ public class UserService { - returns: A request to get the user transactions. */ static func getUserTransactions(range: String) -> Request { - return UpholdClient().get("/v0/me/transactions").set("Range", range) + return UpholdClient().get(url: "/v0/me/transactions").set(key: "Range", value: range) } /** @@ -89,8 +89,8 @@ public class UserService { - returns: A request to update the user information. */ - static func updateUser(updatefields: AnyObject) -> Request { - return UpholdClient().patch("/v0/me").send(updatefields) + static func updateUser(updatefields: Any) -> Request { + return UpholdClient().patch(url: "/v0/me").send(data: updatefields) } } diff --git a/Source/Util/Header.swift b/Source/Util/Header.swift index a90c1c5..134883b 100644 --- a/Source/Util/Header.swift +++ b/Source/Util/Header.swift @@ -2,7 +2,7 @@ import Foundation import SwiftClient /// Header util class. -public class Header { +open class Header { /** Builds the authorization header. @@ -11,7 +11,7 @@ public class Header { - returns: The authorization header. */ - public static func buildAuthorizationHeader(token: String) -> [String: String] { + open static func buildAuthorizationHeader(token: String) -> [String: String] { return ["authorization": String(format: "Bearer %@", token)] } @@ -23,7 +23,7 @@ public class Header { - returns: The string with the header value. */ - public static func buildRangeHeader(start: Int, end: Int) -> String { + open static func buildRangeHeader(start: Int, end: Int) -> String { return String(format: "items=%i-%i", start, end) } @@ -32,7 +32,7 @@ public class Header { - returns: The default headers. */ - public static func getDefaultHeaders() -> [String: String] { + open static func getDefaultHeaders() -> [String: String] { let headers: [String: String] = ["user-agent": String(format: "uphold-ios-sdk/%@ (%@)", GlobalConfigurations.UPHOLD_SDK_VERSION, GlobalConfigurations.SDK_GITHUB_URL)] return headers @@ -60,7 +60,7 @@ public class Header { - returns: The rate limit reset time. */ - public static func getSecondsUntilRateLimitReset(headers: [String: String]) -> String? { + open static func getSecondsUntilRateLimitReset(headers: [String: String]) -> String? { guard let resetTime = headers["retry-after"] else { return nil } @@ -75,12 +75,12 @@ public class Header { - returns: The total number of elements. */ - public static func getTotalNumberOfResults(headers: [String: String]) -> Int? { + open static func getTotalNumberOfResults(headers: [String: String]) -> Int? { guard let contentRange = headers["content-range"] else { return nil } - return NSString(string: contentRange.substringFromIndex(contentRange.rangeOfString("/")!.endIndex)).integerValue + return NSString(string: contentRange.substring(from: contentRange.range(of: "/")!.upperBound)).integerValue } } diff --git a/Source/Util/ResourcesUtil.swift b/Source/Util/ResourcesUtil.swift index 354685f..a92f767 100644 --- a/Source/Util/ResourcesUtil.swift +++ b/Source/Util/ResourcesUtil.swift @@ -1,7 +1,7 @@ import Foundation /// Resources util class. -public class ResourcesUtil { +open class ResourcesUtil { /// The SwiftLint rules that must be disabled. // swiftlint:disable force_try @@ -16,22 +16,22 @@ public class ResourcesUtil { - returns: The configuration value. */ - public static func getValueFromKey(file: String, key: String) throws -> String { + open static func getValueFromKey(file: String, key: String) throws -> String { switch file { case "ConfigurationsPlist": - guard let configurationsPath = NSBundle(forClass: self).pathForResource("Configurations", ofType: "plist"), configurationDictionary = NSDictionary(contentsOfFile: configurationsPath), value = configurationDictionary[key] as? String else { - throw ConfigurationMissingError(message: String(format: "There is no value for the key: %@", key)) + guard let configurationsPath = Bundle(for: self).path(forResource: "Configurations", ofType: "plist"), let configurationDictionary = NSDictionary(contentsOfFile: configurationsPath), let value = configurationDictionary[key] as? String else { + throw ConfigurationMissingError(message: String(format: "There is no value for the key: %@", key)) as Error } return value case "InfoPlist": - guard let infoDictionary = NSBundle(forClass: self).infoDictionary, value = infoDictionary[key] as? String else { - throw ConfigurationMissingError(message: String(format: "There is no value for the key: %@", key)) + guard let infoDictionary = Bundle(for: self).infoDictionary, let value = infoDictionary[key] as? String else { + throw ConfigurationMissingError(message: String(format: "There is no value for the key: %@", key)) as Error } return value default: - throw ConfigurationMissingError(message: String(format: "There is no value for the key: %@", key)) + throw ConfigurationMissingError(message: String(format: "There is no value for the key: %@", key)) as Error } } @@ -42,8 +42,8 @@ public class ResourcesUtil { - returns: The configuration value. */ - public static func getValueFromConfigurationsPlist(key: String) -> String { - return try! ResourcesUtil.getValueFromKey("ConfigurationsPlist", key: key) + open static func getValueFromConfigurationsPlist(key: String) -> String { + return try! ResourcesUtil.getValueFromKey(file: "ConfigurationsPlist", key: key) } /** @@ -53,8 +53,8 @@ public class ResourcesUtil { - returns: The configuration value. */ - public static func getValueFromInfoPlist(key: String) -> String { - return try! ResourcesUtil.getValueFromKey("InfoPlist", key: key) + open static func getValueFromInfoPlist(key: String) -> String { + return try! ResourcesUtil.getValueFromKey(file: "InfoPlist", key: key) } } diff --git a/Source/Util/URLUtils.swift b/Source/Util/URLUtils.swift index 91cb325..10f9bc9 100644 --- a/Source/Util/URLUtils.swift +++ b/Source/Util/URLUtils.swift @@ -1,7 +1,7 @@ import Foundation /// URL utils class. -public class URLUtils { +open class URLUtils { /** Escapes the given URL string and generates an NSURL. @@ -12,9 +12,9 @@ public class URLUtils { - returns: The escaped NSURL. */ - public static func escapeURL(url: String) throws -> NSURL { - guard let escapedUrl = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()), uri = NSURL(string: escapedUrl) else { - throw MalformedUrlError(message: "Invalid URL.") + open static func escapeURL(url: String) throws -> URL { + guard let escapedUrl = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let uri = URL(string: escapedUrl) else { + throw MalformedUrlError(message: "Invalid URL.") as Error } return uri diff --git a/Tests/Integration/Paginator/PaginatorTest.swift b/Tests/Integration/Paginator/PaginatorTest.swift deleted file mode 100644 index 39f233b..0000000 --- a/Tests/Integration/Paginator/PaginatorTest.swift +++ /dev/null @@ -1,78 +0,0 @@ -import XCTest -import PromiseKit -@testable import UpholdSdk - -/// Paginator integration tests. -class PaginatorTest: UpholdTestCase { - - let paginator: Paginator = Paginator(countClosure: { () -> Promise in - return Promise { fulfill, reject in - fulfill(10) - } - }, - elements: Promise { fulfill, reject in - fulfill([AnyObject]()) - }, - hasNextPageClosure: { (currentPage) -> Promise in - return Promise { fulfill, reject in - fulfill(true) - } - }, - nextPageClosure: { (range) -> Promise<[AnyObject]> in - return Promise { fulfill, reject in - let arrayObject = ["foo", "bar"] - fulfill(arrayObject) - } - }) - - func testCount() { - let expectation = expectationWithDescription("Paginator test.") - - paginator.count().then { (count: Int) -> () in - XCTAssertEqual(count, 10, "Failed: Wrong object.") - - expectation.fulfill() - } - - wait() - } - - func testGetNext() { - let expectation = expectationWithDescription("Paginator test.") - - paginator.getNext().then { (objects: [AnyObject]) -> () in - XCTAssertEqual(objects[0] as? String, "foo", "Failed: Wrong object.") - XCTAssertEqual(objects[1] as? String, "bar", "Failed: Wrong object.") - - expectation.fulfill() - } - - wait() - } - - func testGetNextPage() { - let expectation = expectationWithDescription("Paginator test.") - - paginator.nextPageClosure(range: "foobar").then { (objects: [AnyObject]) -> () in - XCTAssertEqual(objects[0] as? String, "foo", "Failed: Wrong object.") - XCTAssertEqual(objects[1] as? String, "bar", "Failed: Wrong object.") - - expectation.fulfill() - } - - wait() - } - - func testHasNextPage() { - let expectation = expectationWithDescription("Paginator test.") - - paginator.hasNextPageClosure(currentPage: 1).then { (hasNext: Bool) -> () in - XCTAssertTrue(hasNext, "Failed: Wrong object.") - - expectation.fulfill() - } - - wait() - } - -} diff --git a/Tests/Integration/Client/SessionManagerTest.swift b/Tests/IntegrationTests/ClientTests/SessionManagerTest.swift similarity index 56% rename from Tests/Integration/Client/SessionManagerTest.swift rename to Tests/IntegrationTests/ClientTests/SessionManagerTest.swift index 8a046e8..2984ab7 100644 --- a/Tests/Integration/Client/SessionManagerTest.swift +++ b/Tests/IntegrationTests/ClientTests/SessionManagerTest.swift @@ -11,13 +11,13 @@ class SessionManagerTest: UpholdTestCase { func testGetBearerTokenShouldReturnNil() { _ = UpholdClient() - XCTAssertNil(SessionManager.sharedInstance.getBearerToken(), "Failed: Wrong token.") + XCTAssertNil(MockSessionManager.sharedInstance.getBearerToken(), "Failed: Wrong token.") } func testGetBearerTokenShouldReturnToken() { - _ = UpholdClient(bearerToken: "foo") + _ = MockUpholdClient(bearerToken: "foo") - guard let token = SessionManager.sharedInstance.getBearerToken() else { + guard let token = MockSessionManager.sharedInstance.getBearerToken() else { XCTFail("The bearer token should not be nil.") return @@ -27,26 +27,26 @@ class SessionManagerTest: UpholdTestCase { } func testInvalidateSessionShouldRemoveToken() { - let client = UpholdClient(bearerToken: "foo") + let client = MockUpholdClient(bearerToken: "foo") - SessionManager.sharedInstance.invalidateSession() + MockSessionManager.sharedInstance.invalidateSession() - let request = client.token.adapter.buildRequest(TickerService.getAllTickers()) + let request = client.mockToken.mockAdapter.buildRequest(request: TickerService.getAllTickers()) XCTAssertNil(request.headers["authorization"], "Failed: Wrong header.") - XCTAssertNil(SessionManager.sharedInstance.getBearerToken(), "Failed: Wrong token.") + XCTAssertNil(MockSessionManager.sharedInstance.getBearerToken(), "Failed: Wrong token.") } func testUpholdClientShouldNotSetToken() { let client = UpholdClient() - let request = client.token.adapter.buildRequest(TickerService.getAllTickers()) + let request = client.token.adapter.buildRequest(request: TickerService.getAllTickers()) XCTAssertNil(request.headers["authorization"], "Failed: Wrong header.") } func testUpholdClientWithTokenShouldSetToken() { - let client = UpholdClient(bearerToken: "foo") - let request = client.token.adapter.buildRequest(TickerService.getAllTickers()) + let client = MockUpholdClient(bearerToken: "foo") + let request = client.mockToken.mockAdapter.buildRequest(request: TickerService.getAllTickers()) guard let header = request.headers["authorization"] else { XCTFail("Authorization header should not be nil.") @@ -58,7 +58,7 @@ class SessionManagerTest: UpholdTestCase { } override func tearDown() { - SessionManager.sharedInstance.invalidateSession() + MockSessionManager.sharedInstance.invalidateSession() } } diff --git a/Tests/Integration/Client/UpholdClientTest.swift b/Tests/IntegrationTests/ClientTests/UpholdClientTest.swift similarity index 80% rename from Tests/Integration/Client/UpholdClientTest.swift rename to Tests/IntegrationTests/ClientTests/UpholdClientTest.swift index d19e525..ba09029 100644 --- a/Tests/Integration/Client/UpholdClientTest.swift +++ b/Tests/IntegrationTests/ClientTests/UpholdClientTest.swift @@ -11,17 +11,18 @@ class UpholdClientTest: UpholdTestCase { override func tearDown() { super.tearDown() - SessionManager.sharedInstance.invalidateSession() + MockSessionManager.sharedInstance.invalidateSession() } func testCompleteAuthorizationShouldReturnEmptyCodeError() { + let testExpectation = expectation(description: "Uphold client authorization test.") + let authenticationResponse = AuthenticationResponse(accessToken: "foo", expiresIn: 1234, scope: "foobar", tokenType: "bar") - let authorizationViewController = AuthorizationViewController(URL: NSURL(string: "http://foo.bar")!, entersReaderIfAvailable: false) + let authorizationViewController = AuthorizationViewController(url: URL(string: "http://foo.bar")!, entersReaderIfAvailable: false) let client = UpholdClient() - let expectation = expectationWithDescription("Uphold client authorization test.") client.token.adapter = MockRestAdapter(body: Mapper().toJSONString(authenticationResponse)!) - client.completeAuthorization(authorizationViewController, clientId: "foo", clientSecret: "bar", grantType: "foobiz", state: "foobar", uri: NSURL(string: "uphold://foobar.com?state=foobar")!).error { (error: ErrorType) -> Void in + client.completeAuthorization(authorizationViewController: authorizationViewController, clientId: "foo", clientSecret: "bar", grantType: "foobiz", state: "foobar", uri: URL(string: "uphold://foobar.com?state=foobar")!).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -31,20 +32,21 @@ class UpholdClientTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "URL query parameter code should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCompleteAuthorizationShouldReturnEmptyStateError() { + let testExpectation = expectation(description: "Uphold client authorization test.") + let authenticationResponse = AuthenticationResponse(accessToken: "foo", expiresIn: 1234, scope: "foobar", tokenType: "bar") - let authorizationViewController = AuthorizationViewController(URL: NSURL(string: "http://foo.bar")!, entersReaderIfAvailable: false) + let authorizationViewController = AuthorizationViewController(url: URL(string: "http://foo.bar")!, entersReaderIfAvailable: false) let client = UpholdClient() - let expectation = expectationWithDescription("Uphold client authorization test.") client.token.adapter = MockRestAdapter(body: Mapper().toJSONString(authenticationResponse)!) - client.completeAuthorization(authorizationViewController, clientId: "foo", clientSecret: "bar", grantType: "foobiz", state: "foobar", uri: NSURL(string: "uphold://foobar.com?code=foo")!).error { (error: ErrorType) -> Void in + client.completeAuthorization(authorizationViewController: authorizationViewController, clientId: "foo", clientSecret: "bar", grantType: "foobiz", state: "foobar", uri: URL(string: "uphold://foobar.com?code=foo")!).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -54,34 +56,38 @@ class UpholdClientTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "URL query parameter state should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCompleteAuthorizationShouldReturnTheAuthenticationResponse() { + let testExpectation = expectation(description: "Uphold client authorization test.") + let authenticationResponse = AuthenticationResponse(accessToken: "foo", expiresIn: 1234, scope: "foobar", tokenType: "bar") - let authorizationViewController = AuthorizationViewController(URL: NSURL(string: "http://foo.bar")!, entersReaderIfAvailable: false) + let authorizationViewController = AuthorizationViewController(url: URL(string: "http://foo.bar")!, entersReaderIfAvailable: false) let client = UpholdClient() - let expectation = expectationWithDescription("Uphold client authorization test.") client.token.adapter = MockRestAdapter(body: Mapper().toJSONString(authenticationResponse)!) - client.completeAuthorization(authorizationViewController, clientId: "foo", clientSecret: "bar", grantType: "foobiz", state: "foobar", uri: NSURL(string: "uphold://foobar.com?code=foo&state=foobar")!).then { (authenticationResponse: AuthenticationResponse) -> () in + client.completeAuthorization(authorizationViewController: authorizationViewController, clientId: "foo", clientSecret: "bar", grantType: "foobiz", state: "foobar", uri: URL(string: "uphold://foobar.com?code=foo&state=foobar")!).then { (authenticationResponse: AuthenticationResponse) -> Void in XCTAssertEqual(authenticationResponse.accessToken, "foo", "Failed: Wrong access token.") XCTAssertEqual(authenticationResponse.expiresIn, 1234, "Failed: Wrong expiration time.") XCTAssertEqual(authenticationResponse.scope, "foobar", "Failed: Wrong scope.") XCTAssertEqual(authenticationResponse.tokenType, "bar", "Failed: Wrong token type.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold client authorization test error.") + }) wait() } func testGetTickersShouldReturnTheArrayOfTickers() { - let expectation = expectationWithDescription("Uphold client test.") + let testExpectation = expectation(description: "Uphold client test.") + let json: String = "[{" + "\"ask\": \"foo\"," + "\"bid\": \"bar\"," + @@ -101,7 +107,7 @@ class UpholdClientTest: UpholdTestCase { let client = UpholdClient() client.token.adapter = MockRestAdapter(body: json) - client.getTickers().then { (rates: [Rate]) -> () in + client.getTickers().then { (rates: [Rate]) -> Void in XCTAssertEqual(rates.count, 3, "Failed: Wrong response object size.") XCTAssertEqual(rates[0].ask, "foo", "Failed: Wrong response object attribute.") XCTAssertEqual(rates[0].bid, "bar", "Failed: Wrong response object attribute.") @@ -116,14 +122,17 @@ class UpholdClientTest: UpholdTestCase { XCTAssertEqual(rates[2].currency, "bar", "Failed: Wrong response object attribute.") XCTAssertEqual(rates[2].pair, "foo", "Failed: Wrong response object attribute.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold client test error.") + }) wait() } func testGetTickersByCurrencyShouldReturnTheArrayOfTickers() { - let expectation = expectationWithDescription("Uphold client test.") + let testExpectation = expectation(description: "Uphold client test.") + let json: String = "[{" + "\"ask\": \"foo\"," + "\"bid\": \"bar\"," + @@ -143,20 +152,23 @@ class UpholdClientTest: UpholdTestCase { let client = UpholdClient() client.token.adapter = MockRestAdapter(body: json) - client.getTickersByCurrency("USD").then { (rates: [Rate]) -> () in + client.getTickersByCurrency(currency: "USD").then { (rates: [Rate]) -> Void in XCTAssertEqual(rates.count, 3, "Failed: Wrong response object size.") XCTAssertEqual(rates[0].ask, "foo", "Failed: Wrong response object attribute.") XCTAssertEqual(rates[1].ask, "fiz", "Failed: Wrong response object attribute.") XCTAssertEqual(rates[2].ask, "foobar", "Failed: Wrong response object attribute.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold client test error.") + }) wait() } func testGetUserShouldReturnTheUser() { - let expectation = expectationWithDescription("Uphold client test.") + let testExpectation = expectation(description: "Uphold client test.") + let json: String = "{" + "\"username\": \"foobar\"," + "\"email\": \"foo@bar.org\"," + @@ -205,10 +217,10 @@ class UpholdClientTest: UpholdTestCase { "}" + "}" + "}" - let client = UpholdClient(bearerToken: "foobar") - client.token.adapter = MockRestAdapter(body: json) + let client = MockUpholdClient(bearerToken: "foobar") + client.mockToken.mockAdapter = MockRestAdapter(body: json) - client.getUser().then { (user: User) -> () in + client.getUser().then { (user: User) -> Void in XCTAssertEqual(user.country, "BAR", "Failed: User country didn't match.") XCTAssertEqual(user.currencies!.count, 1, "Failed: User currencies didn't match.") XCTAssertEqual(user.currencies![0], "BTC", "Failed: User currencies didn't match.") @@ -231,8 +243,10 @@ class UpholdClientTest: UpholdTestCase { XCTAssertEqual(user.status, "ok", "Failed: User name didn't match.") XCTAssertEqual(user.username, "foobar", "Failed: User name didn't match.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold client test error.") + }) wait() } @@ -242,7 +256,7 @@ class UpholdClientTest: UpholdTestCase { client.invalidateSession() - let request = client.token.adapter.buildRequest(TickerService.getAllTickers()) + let request = client.token.adapter.buildRequest(request: TickerService.getAllTickers()) XCTAssertNil(request.headers["authorization"], "Failed: Wrong header.") XCTAssertNil(KeychainSwift().get(SessionManager.KEYCHAIN_TOKEN_KEY), "Failed: Wrong token.") diff --git a/Tests/Integration/Client/UpholdRestAdapterTest.swift b/Tests/IntegrationTests/ClientTests/UpholdRestAdapterTest.swift similarity index 59% rename from Tests/Integration/Client/UpholdRestAdapterTest.swift rename to Tests/IntegrationTests/ClientTests/UpholdRestAdapterTest.swift index 13b3451..7bf5eee 100644 --- a/Tests/Integration/Client/UpholdRestAdapterTest.swift +++ b/Tests/IntegrationTests/ClientTests/UpholdRestAdapterTest.swift @@ -8,8 +8,8 @@ import UpholdSdk class UpholdRestAdapterTest: UpholdTestCase { func testBuildRequestShouldReturnRequest() { - let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) + let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) XCTAssertEqual(request.headers["user-agent"], String(format: "uphold-ios-sdk/%@ (%@)", GlobalConfigurations.UPHOLD_SDK_VERSION, GlobalConfigurations.SDK_GITHUB_URL), "Failed: Wrong headers.") XCTAssertEqual(request.method, "foo", "Failed: Wrong method.") @@ -17,281 +17,299 @@ class UpholdRestAdapterTest: UpholdTestCase { } func testBuildEmptyResponseShouldReturnBadRequestError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") - let mockRequest = MockRequest(body: nil, code: 400, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request) + let testExpectation = expectation(description: "Uphold REST adapter response test.") - promise.recover { (error: ErrorType) -> Promise in + let mockRequest = MockRequest(body: nil, code: 400, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request: request) + + promise.catch(execute: { (error: Error) in guard let badRequestError = error as? BadRequestError else { XCTFail("Error should be BadRequestError.") - return promise + return } XCTAssertEqual(badRequestError.code, 400, "Failed: Wrong response HTTP status code.") XCTAssertEqual(badRequestError.info["Bad request error"], "HTTP error 400 - Bad request.", "Failed: Wrong message.") - expectation.fulfill() - - return promise - } + testExpectation.fulfill() + }) wait() } func testBuildEmptyResponseShouldReturnFulfilledPromise() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") - let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request) + let testExpectation = expectation(description: "Uphold REST adapter response test.") - promise.then { (response: Response) -> () in - XCTAssertEqual(response.basicStatus, Response.BasicResponseType.OK, "Failed: Wrong response basic status code.") + let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request: request) + + promise.then { (response: Response) -> Void in + XCTAssertEqual(response.basicStatus, Response.BasicResponseType.ok, "Failed: Wrong response basic status code.") XCTAssertNil(response.text, "Failed: Wrong response body.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold REST adapter response test error.") + }) wait() } func testBuildEmptyResponseWithBodyShouldReturnFulfilledPromise() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") - let mockRequest = MockRequest(body: "", code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request) + let testExpectation = expectation(description: "Uphold REST adapter response test.") + + let mockRequest = MockRequest(body: "", code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request: request) - promise.then { (response: Response) -> () in - XCTAssertEqual(response.basicStatus, Response.BasicResponseType.OK, "Failed: Wrong response basic status code.") + promise.then { (response: Response) -> Void in + XCTAssertEqual(response.basicStatus, Response.BasicResponseType.ok, "Failed: Wrong response basic status code.") XCTAssertEqual(response.text, "", "Failed: Wrong response body.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold REST adapter response test error.") + }) wait() } func testBuildEmptyResponseShouldReturnLogicError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") - let mockRequest = MockRequest(body: "foobar", code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request) + let testExpectation = expectation(description: "Uphold REST adapter response test.") - promise.recover { (error: ErrorType) -> Promise in + let mockRequest = MockRequest(body: "foobar", code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildEmptyResponse(request: request) + + promise.catch(execute: { (error: Error) in guard let logicError = error as? LogicError else { XCTFail("Error should be LogicError.") - return promise + return } XCTAssertEqual(logicError.info, ["Logic error": "Response body should be empty."], "Failed: Wrong error message.") XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.") - expectation.fulfill() + testExpectation.fulfill() - return promise - } + return + }) wait() } func testBuildResponseShouldReturnBadRequestError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") + let testExpectation = expectation(description: "Uphold REST adapter response test.") + let json = "{" + "\"ask\":\"1.2\"," + "\"bid\":\"1\"," + "\"currency\":\"BTC\"," + "\"pair\":\"BTCBTC\"" + "}" - let mockRequest = MockRequest(body: json, code: 400, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildResponse(request) + let mockRequest = MockRequest(body: json, code: 400, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildResponse(request: request) - promise.recover { (error: ErrorType) -> Promise in + promise.catch(execute: { (error: Error) in guard let badRequestError = error as? BadRequestError else { XCTFail("Error should be BadRequestError.") - return promise + return } XCTAssertEqual(badRequestError.code, 400, "Failed: Wrong response HTTP status code.") XCTAssertEqual(badRequestError.info["Bad request error"], "HTTP error 400 - Bad request.", "Failed: Wrong message.") - expectation.fulfill() + testExpectation.fulfill() - return promise - } + return + }) wait() } func testBuildResponseShouldReturnEmptyBodyLogicError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") - let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildResponse(request) + let testExpectation = expectation(description: "Uphold REST adapter response test.") + + let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildResponse(request: request) - promise.recover { (error: ErrorType) -> Promise in + promise.catch(execute: { (error: Error) in guard let logicError = error as? LogicError else { XCTFail("Error should be LogicError.") - return promise + return } XCTAssertEqual(logicError.info, ["Logic error": "Response body should not be empty."], "Failed: Wrong error message.") XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.") - expectation.fulfill() + testExpectation.fulfill() - return promise - } + return + }) wait() } func testBuildResponseShouldReturnFailedMapLogicError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") + let testExpectation = expectation(description: "Uphold REST adapter response test.") + let json = "{[" + "\"ask\":\"1.2\"," + "\"bid\":\"1\"," + "\"currency\":\"BTC\"," + "\"pair\":\"BTCBTC\"" + "}" - let mockRequest = MockRequest(body: json, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildResponse(request) + let mockRequest = MockRequest(body: json, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildResponse(request: request) - promise.recover { (error: ErrorType) -> Promise in + promise.catch(execute: { (error: Error) in guard let logicError = error as? LogicError else { XCTFail("Error should be LogicError.") - return promise + return } XCTAssertEqual(logicError.info, ["Logic error": "Failed to map the JSON object."], "Failed: Wrong error message.") XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.") - expectation.fulfill() + testExpectation.fulfill() - return promise - } + return + }) wait() } func testBuildResponseShouldReturnFulfilledPromise() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") + let testExpectation = expectation(description: "Uphold REST adapter response test.") + let json = "{" + "\"ask\":\"1.2\"," + "\"bid\":\"1\"," + "\"currency\":\"BTC\"," + "\"pair\":\"BTCBTC\"" + "}" - let mockRequest = MockRequest(body: json, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise = UpholdRestAdapter().buildResponse(request) + let mockRequest = MockRequest(body: json, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise = UpholdRestAdapter().buildResponse(request: request) - promise.then { (rate: Rate) -> () in + promise.then { (rate: Rate) -> Void in XCTAssertEqual(rate.ask, "1.2", "Failed: Wrong response object attribute.") XCTAssertEqual(rate.bid, "1", "Failed: Wrong response object attribute.") XCTAssertEqual(rate.currency, "BTC", "Failed: Wrong response object attribute.") XCTAssertEqual(rate.pair, "BTCBTC", "Failed: Wrong response object attribute.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold REST adapter response test error.") + }) wait() } func testBuildResponseArrayShouldReturnBadRequestError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") + let testExpectation = expectation(description: "Uphold REST adapter response test.") + let json = "[{\"ask\":\"1\"}, {\"ask\":\"440.99\"}]" - let mockRequest = MockRequest(body: json, code: 400, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request) + let mockRequest = MockRequest(body: json, code: 400, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request) - promise.recover { (error: ErrorType) -> Promise<[Rate]> in + promise.catch(execute: { (error: Error) in guard let badRequestError = error as? BadRequestError else { XCTFail("Error should be BadRequestError.") - return promise + return } XCTAssertEqual(badRequestError.code, 400, "Failed: Wrong response HTTP status code.") XCTAssertEqual(badRequestError.info["Bad request error"], "HTTP error 400 - Bad request.", "Failed: Wrong message.") - expectation.fulfill() + testExpectation.fulfill() - return promise - } + return + }) wait() } func testBuildResponseArrayShouldReturnEmptyBodyLogicError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") - let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request) + let testExpectation = expectation(description: "Uphold REST adapter response test.") - promise.recover { (error: ErrorType) -> Promise<[Rate]> in + let mockRequest = MockRequest(body: nil, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request) + + promise.catch(execute: { (error: Error) in guard let logicError = error as? LogicError else { XCTFail("Error should be LogicError.") - return promise + return } XCTAssertEqual(logicError.info, ["Logic error": "Response body should not be empty."], "Failed: Wrong error message.") XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.") - expectation.fulfill() + testExpectation.fulfill() - return promise - } + return + }) wait() } func testBuildResponseArrayShouldReturnFailedMapLogicError() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") + let testExpectation = expectation(description: "Uphold REST adapter response test.") + let jsonRates = "[[{\"ask\":\"1\"}, {\"ask\":\"440.99\"}]" - let mockRequest = MockRequest(body: jsonRates, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request) + let mockRequest = MockRequest(body: jsonRates, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request) - promise.recover { (error: ErrorType) -> Promise<[Rate]> in + promise.catch(execute: { (error: Error) in guard let logicError = error as? LogicError else { XCTFail("Error should be LogicError.") - return promise + return } XCTAssertEqual(logicError.info, ["Logic error": "Failed to map the JSON object."], "Failed: Wrong error message.") XCTAssertNil(logicError.code, "Failed: Wrong response HTTP status code.") - expectation.fulfill() + testExpectation.fulfill() - return promise - } + return + }) wait() } func testBuildResponseArrayShouldReturnFulfilledPromise() { - let expectation = expectationWithDescription("Uphold REST adapter response test.") + let testExpectation = expectation(description: "Uphold REST adapter response test.") + let jsonRates = "[{\"ask\":\"1\"}, {\"ask\":\"440.99\"}]" - let mockRequest = MockRequest(body: jsonRates, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: nil, method: "foo") - let request = UpholdRestAdapter().buildRequest(mockRequest) - let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request) + let mockRequest = MockRequest(body: jsonRates, code: 200, errorHandler: {(_: Error) -> Void in}, headers: nil, method: "foo") + let request = UpholdRestAdapter().buildRequest(request: mockRequest) + let promise: Promise<[Rate]> = UpholdRestAdapter().buildResponse(request: request) - promise.then { (rates: [Rate]) -> () in + promise.then { (rates: [Rate]) -> Void in XCTAssertEqual(rates.count, 2, "Failed: Wrong response object size.") XCTAssertEqual(rates[0].ask, "1", "Failed: Wrong response object attribute.") XCTAssertEqual(rates[1].ask, "440.99", "Failed: Wrong response object attribute.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Uphold REST adapter response test error.") + }) wait() } diff --git a/Tests/Integration/ErrorHandling/UpholdClientErrorHandlingTest.swift b/Tests/IntegrationTests/ErrorHandlingTests/UpholdClientErrorHandlingTest.swift similarity index 83% rename from Tests/Integration/ErrorHandling/UpholdClientErrorHandlingTest.swift rename to Tests/IntegrationTests/ErrorHandlingTests/UpholdClientErrorHandlingTest.swift index 8d722ea..b683ca0 100644 --- a/Tests/Integration/ErrorHandling/UpholdClientErrorHandlingTest.swift +++ b/Tests/IntegrationTests/ErrorHandlingTests/UpholdClientErrorHandlingTest.swift @@ -5,23 +5,23 @@ import UpholdSdk /// UpholdClientErrorHandling integration tests. class UpholdClientErrorHandlingTest: UpholdTestCase { - var defaultError: ((NSError) -> Void)! + var defaultError: ((Error) -> Void)! var expectation: XCTestExpectation! override func setUp() { super.setUp() - defaultError = {(error: NSError) -> Void in + defaultError = {(error: Error) -> Void in XCTFail("Request should succeed. Failed with error \(error).") self.expectation.fulfill() } - expectation = expectationWithDescription("Status code") + expectation = expectation(description: "Status code") } func testHandleErrorShouldReturnApiLimitExceedError() { let done = { (response: Response) -> Void in - let error = UpholdClientErrorHandling.handleError(response) + let error = UpholdClientErrorHandling.handleError(response: response) XCTAssertNotNil(error as? ApiLimitExceedError, "Failed: Wrong class type.") XCTAssertEqual(error.code, 429, "Failed: Wrong HTTP error code.") @@ -30,14 +30,14 @@ class UpholdClientErrorHandlingTest: UpholdTestCase { self.expectation.fulfill() } - MockRequest(body: "body", code: 429, errorHandler: { (error: NSError) -> Void in }, headers: ["rate-limit-total": "300", "retry-after": "10"], method: "foo").end(done, onError: self.defaultError) + MockRequest(body: "body", code: 429, errorHandler: { (_: Error) -> Void in }, headers: ["rate-limit-total": "300", "retry-after": "10"], method: "foo").end(done: done, onError: self.defaultError) wait() } func testHandleErrorShouldReturnAuthenticationError() { let done = { (response: Response) -> Void in - let error = UpholdClientErrorHandling.handleError(response) + let error = UpholdClientErrorHandling.handleError(response: response) XCTAssertNotNil(error as? AuthenticationError, "Failed: Wrong class type.") XCTAssertEqual(error.code, 401, "Failed: Wrong HTTP error code.") @@ -46,14 +46,14 @@ class UpholdClientErrorHandlingTest: UpholdTestCase { self.expectation.fulfill() } - MockRequest(body: "body", code: 401, errorHandler: { (error: NSError) -> Void in }, headers: nil, method: "foo").end(done, onError: self.defaultError) + MockRequest(body: "body", code: 401, errorHandler: { (_: Error) -> Void in }, headers: nil, method: "foo").end(done: done, onError: self.defaultError) wait() } func testHandleErrorShouldReturnAuthenticationTimeoutError() { let done = { (response: Response) -> Void in - let error = UpholdClientErrorHandling.handleError(response) + let error = UpholdClientErrorHandling.handleError(response: response) XCTAssertNotNil(error as? BadRequestError, "Failed: Wrong class type.") XCTAssertEqual(error.code, 419, "Failed: Wrong HTTP error code.") @@ -62,14 +62,14 @@ class UpholdClientErrorHandlingTest: UpholdTestCase { self.expectation.fulfill() } - MockRequest(body: "body", code: 419, errorHandler: { (error: NSError) -> Void in }, headers: nil, method: "foo").end(done, onError: self.defaultError) + MockRequest(body: "body", code: 419, errorHandler: { (_: Error) -> Void in }, headers: nil, method: "foo").end(done: done, onError: self.defaultError) wait() } func testHandleErrorShouldReturnBadRequestError() { let done = { (response: Response) -> Void in - let error = UpholdClientErrorHandling.handleError(response) + let error = UpholdClientErrorHandling.handleError(response: response) XCTAssertNotNil(error as? BadRequestError, "Failed: Wrong class type.") XCTAssertEqual(error.code, 400, "Failed: Wrong HTTP error code.") @@ -78,7 +78,7 @@ class UpholdClientErrorHandlingTest: UpholdTestCase { self.expectation.fulfill() } - MockRequest(body: "body", code: 400, errorHandler: { (error: NSError) -> Void in }, headers: nil, method: "foo").end(done, onError: self.defaultError) + MockRequest(body: "body", code: 400, errorHandler: { (_: Error) -> Void in }, headers: nil, method: "foo").end(done: done, onError: self.defaultError) wait() } @@ -118,7 +118,7 @@ class UpholdClientErrorHandlingTest: UpholdTestCase { func testHandleErrorShouldReturnNotFoundError() { let done = { (response: Response) -> Void in - let error = UpholdClientErrorHandling.handleError(response) + let error = UpholdClientErrorHandling.handleError(response: response) XCTAssertNotNil(error as? NotFoundError, "Failed: Wrong class type.") XCTAssertEqual(error.code, 404, "Failed: Wrong HTTP error code.") @@ -127,14 +127,14 @@ class UpholdClientErrorHandlingTest: UpholdTestCase { self.expectation.fulfill() } - MockRequest(body: "body", code: 404, errorHandler: { (error: NSError) -> Void in }, headers: nil, method: "foo").end(done, onError: self.defaultError) + MockRequest(body: "body", code: 404, errorHandler: { (_: Error) -> Void in }, headers: nil, method: "foo").end(done: done, onError: self.defaultError) wait() } func testHandleErrorShouldReturnPreConditionFailError() { let done = { (response: Response) -> Void in - let error = UpholdClientErrorHandling.handleError(response) + let error = UpholdClientErrorHandling.handleError(response: response) XCTAssertNotNil(error as? BadRequestError, "Failed: Wrong class type.") XCTAssertEqual(error.code, 412, "Failed: Wrong HTTP error code.") @@ -143,7 +143,7 @@ class UpholdClientErrorHandlingTest: UpholdTestCase { self.expectation.fulfill() } - MockRequest(body: "body", code: 412, errorHandler: { (error: NSError) -> Void in }, headers: nil, method: "foo").end(done, onError: self.defaultError) + MockRequest(body: "body", code: 412, errorHandler: { (_: Error) -> Void in }, headers: nil, method: "foo").end(done: done, onError: self.defaultError) wait() } diff --git a/Tests/Integration/Model/CardTest.swift b/Tests/IntegrationTests/ModelTests/CardTest.swift similarity index 76% rename from Tests/Integration/Model/CardTest.swift rename to Tests/IntegrationTests/ModelTests/CardTest.swift index 3555105..c503f3b 100644 --- a/Tests/Integration/Model/CardTest.swift +++ b/Tests/IntegrationTests/ModelTests/CardTest.swift @@ -32,7 +32,7 @@ class CardTest: UpholdTestCase { "\"currency\": \"USD\"" + "}]" + "}" - let card = Mapper().map(json) + let card = Mapper().map(JSONString: json) XCTAssertEqual(card!.id!, "foobar", "Failed: Card id didn't match.") XCTAssertFalse(card!.address!.isEmpty, "Failed: Address didn't match.") @@ -53,26 +53,30 @@ class CardTest: UpholdTestCase { } func testCreateAddressShouldReturnTheAddress() { + let testExpectation = expectation(description: "User test: create address.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("User test: create address.") card.adapter = MockRestAdapter(body: "{\"id\": \"foo\",\"network\": \"bar\"}") - card.createAddress(AddressRequest(network: "bitcoin")).then { (address: Address) -> () in + card.createAddress(addressRequest: AddressRequest(network: "bitcoin")).then { (address: Address) -> Void in XCTAssertEqual(address.id, "foo", "Failed: Wrong adrress id.") XCTAssertEqual(address.network, "bar", "Failed: Wrong address network.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create address error.") + }) wait() } func testCreateAddressShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! - let expectation = expectationWithDescription("User test: create address.") + let testExpectation = expectation(description: "User test: create address.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - card.createAddress(AddressRequest(network: "bitcoin")).error { (error: ErrorType) -> Void in + card.createAddress(addressRequest: AddressRequest(network: "bitcoin")).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -82,15 +86,16 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCreateTransactionCardDepositShouldReturnTheTransaction() { + let testExpectation = expectation(description: "Card test: create transaction card deposit.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: create transaction card deposit.") let json: String = "{" + "\"id\": \"foobar\"," + "\"type\": \"transfer\"," + @@ -160,7 +165,7 @@ class CardTest: UpholdTestCase { let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionCardDepositRequest = TransactionCardDepositRequest(denomination: transactionDenominationRequest, origin: "foobiz", securityCode: "1234") - card.createTransaction(transactionCardDepositRequest).then { (transaction: Transaction) -> () in + card.createTransaction(transactionRequest: transactionCardDepositRequest).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.createdAt, "2014-08-27T00:01:11.616Z", "Failed: Wrong transaction createdAt.") XCTAssertEqual(transaction.denomination!.amount, "0.1", "Failed: Wrong transaction denomination amount.") XCTAssertEqual(transaction.denomination!.currency, "BTC", "Failed: Wrong transaction denomination currency.") @@ -215,20 +220,23 @@ class CardTest: UpholdTestCase { XCTAssertEqual(transactionCardDepositRequest.origin, "foobiz", "Failed: Wrong transaction card deposit origin.") XCTAssertEqual(transactionCardDepositRequest.securityCode, "1234", "Failed: Wrong transaction card deposit security code.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction card deposit error.") + }) wait() } func testCreateTransactionCardDepositShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! + let testExpectation = expectation(description: "Card test: create transaction transfer.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - let expectation = expectationWithDescription("Card test: create transaction transfer.") let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionCardDepositRequest = TransactionCardDepositRequest(denomination: transactionDenominationRequest, origin: "foobar", securityCode: "1234") - card.createTransaction(transactionCardDepositRequest).error { (error: ErrorType) -> Void in + card.createTransaction(transactionRequest: transactionCardDepositRequest).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -238,31 +246,35 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCreateTransactionCardDepositWithCommitShouldReturnTheTransaction() { + let testExpectation = expectation(description: "Card test: create transaction transfer.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: create transaction transfer.") - card.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(["transactionId": "foobar"]))!) + card.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(fields: ["transactionId": "foobar"]))!) let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionCardDepositRequest = TransactionCardDepositRequest(denomination: transactionDenominationRequest, origin: "foobar", securityCode: "1234") - card.createTransaction(true, transactionRequest: transactionCardDepositRequest).then { (transaction: Transaction) -> () in + card.createTransaction(commit: true, transactionRequest: transactionCardDepositRequest).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction id.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction transfer error.") + }) wait() } func testCreateTransactionDepositShouldReturnTheTransaction() { + let testExpectation = expectation(description: "Card test: create transaction deposit.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: create transaction deposit.") let json: String = "{" + "\"id\": \"foobar\"," + "}" @@ -271,24 +283,27 @@ class CardTest: UpholdTestCase { let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionDepositRequest = TransactionDepositRequest(denomination: transactionDenominationRequest, origin: "foobiz") - card.createTransaction(transactionDepositRequest).then { (transaction: Transaction) -> () in + card.createTransaction(transactionRequest: transactionDepositRequest).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction id.") XCTAssertEqual(transactionDepositRequest.origin, "foobiz", "Failed: Wrong transaction origin.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction deposit error.") + }) wait() } func testCreateTransactionDepositShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! + let testExpectation = expectation(description: "Card test: create transaction transfer.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - let expectation = expectationWithDescription("Card test: create transaction transfer.") let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionDepositRequest = TransactionDepositRequest(denomination: transactionDenominationRequest, origin: "foobar") - card.createTransaction(transactionDepositRequest).error { (error: ErrorType) -> Void in + card.createTransaction(transactionRequest: transactionDepositRequest).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -298,31 +313,35 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCreateTransactionDepositWithCommitShouldReturnTheTransaction() { + let testExpectation = expectation(description: "Card test: create transaction transfer.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: create transaction transfer.") - card.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(["transactionId": "foobar"]))!) + card.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(fields: ["transactionId": "foobar"]))!) let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionDepositRequest = TransactionDepositRequest(denomination: transactionDenominationRequest, origin: "foobar") - card.createTransaction(true, transactionRequest: transactionDepositRequest).then { (transaction: Transaction) -> () in + card.createTransaction(commit: true, transactionRequest: transactionDepositRequest).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction id.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction transfer error.") + }) wait() } func testCreateTransactionTransferShouldReturnTheTransaction() { + let testExpectation = expectation(description: "Card test: create transaction transfer.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: create transaction transfer.") let json: String = "{" + "\"id\": \"foobar\"," + "}" @@ -330,24 +349,27 @@ class CardTest: UpholdTestCase { let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionRequest = TransactionTransferRequest(denomination: transactionDenominationRequest, destination: "foobiz") - card.createTransaction(transactionRequest).then { (transaction: Transaction) -> () in + card.createTransaction(transactionRequest: transactionRequest).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction id.") XCTAssertEqual(transactionRequest.destination, "foobiz", "Failed: Wrong transaction destination.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction transfer error.") + }) wait() } func testCreateTransactionTransferShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! + let testExpectation = expectation(description: "Card test: create transaction transfer.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - let expectation = expectationWithDescription("Card test: create transaction transfer.") let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionRequest = TransactionTransferRequest(denomination: transactionDenominationRequest, destination: "foobar") - card.createTransaction(transactionRequest).error { (error: ErrorType) -> Void in + card.createTransaction(transactionRequest: transactionRequest).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -357,34 +379,38 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCreateTransactionTransferWithCommitShouldReturnTheTransaction() { + let testExpectation = expectation(description: "Card test: create transaction transfer.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: create transaction transfer.") - card.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(["transactionId": "foobar"]))!) + card.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(fields: ["transactionId": "foobar"]))!) let transactionDenominationRequest = TransactionDenominationRequest(amount: "foo", currency: "bar") let transactionRequest = TransactionTransferRequest(denomination: transactionDenominationRequest, destination: "foobar") - card.createTransaction(true, transactionRequest: transactionRequest).then { (transaction: Transaction) -> () in + card.createTransaction(commit: true, transactionRequest: transactionRequest).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction id.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction transfer error.") + }) wait() } func testGetTransactionsShouldReturnTheArrayOfTransactions() { + let testExpectation = expectation(description: "Card test: get transactions.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: get transactions.") - card.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!) + card.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!) - card.getTransactions().elements.then({ (transactions: [Transaction]) -> () in + card.getTransactions().elements.then(execute: { (transactions: [Transaction]) -> Void in let mockRestAdapter: MockRestAdapter = (card.adapter as? MockRestAdapter)! XCTAssertEqual(mockRestAdapter.headers!.count, 1, "Failed: Wrong number of headers.") @@ -392,35 +418,43 @@ class CardTest: UpholdTestCase { XCTAssertEqual(transactions[0].id, "foobar", "Failed: Wrong transaction object.") XCTAssertEqual(transactions[1].id, "foobiz", "Failed: Wrong transaction object.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("User test: get transaction error.") }) wait() } func testGetTransactionsShouldReturnThePaginatorCount() { + let testExpectation = expectation(description: "Card test: get transactions.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: get transactions.") card.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(), Fixtures.loadTransaction()])!, headers: ["content-range": "0-2/60"]) - card.getTransactions().count().then({ (count: Int) -> () in + card.getTransactions().count().then(execute: { (count: Int) -> Void in XCTAssertEqual(count, 60, "Failed: Wrong paginator count.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("User test: get transactions error.") }) wait() } func testGetTransactionsShouldReturnThePaginatorHasNext() { + let testExpectation = expectation(description: "Card test: get transactions.") + let card: Card = Fixtures.loadCard() - let expectation = expectationWithDescription("Card test: get transactions.") card.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(), Fixtures.loadTransaction()])!, headers: ["content-range": "0-49/51"]) - card.getTransactions().hasNext().then({ (bool: Bool) -> () in + card.getTransactions().hasNext().then(execute: { (bool: Bool) -> Void in XCTAssertTrue(bool, "Failed: Wrong paginator hasNext value.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("User test: get transactions.") }) wait() @@ -432,11 +466,15 @@ class CardTest: UpholdTestCase { card.adapter = MockRestAdapter(body: Mapper().toJSONString(transactions)!) let paginator: Paginator = card.getTransactions() - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("Paginator get next error.") + }) let firstRequestHeaders = (card.adapter as? MockRestAdapter)!.headers - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("Paginator get next error.") + }) let secondRequestHeaders = (card.adapter as? MockRestAdapter)!.headers @@ -447,11 +485,12 @@ class CardTest: UpholdTestCase { } func testGetTransactionsPaginatorCountShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! + let testExpectation = expectation(description: "Card test: get transactions.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - let expectation = expectationWithDescription("Card test: get transactions.") - card.getTransactions().count().error { (error: ErrorType) -> Void in + card.getTransactions().count().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -461,18 +500,19 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetTransactionsPaginatorElementsShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! + let testExpectation = expectation(description: "Card test: get transactions.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - let expectation = expectationWithDescription("Card test: get transactions.") - card.getTransactions().elements.error { (error: ErrorType) -> Void in + card.getTransactions().elements.catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -482,18 +522,19 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetTransactionsPaginatorGetNextShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! + let testExpectation = expectation(description: "Card test: get transactions.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - let expectation = expectationWithDescription("Card test: get transactions.") - card.getTransactions().getNext().error { (error: ErrorType) -> Void in + card.getTransactions().getNext().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -503,18 +544,19 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetTransactionsPaginatorHasNextShouldReturnUnexpectedResponseError() { - let card: Card = Mapper().map("{}")! + let testExpectation = expectation(description: "Card test: get transactions.") + + let card: Card = Mapper().map(JSONString: "{}")! card.adapter = MockRestAdapter() - let expectation = expectationWithDescription("Card test: get transactions.") - card.getTransactions().hasNext().error { (error: ErrorType) -> Void in + card.getTransactions().hasNext().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -524,22 +566,25 @@ class CardTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Card id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testUpdateShouldReturnTheCard() { - let card: Card = Fixtures.loadCard(["id": "foobar"]) + let testExpectation = expectation(description: "Card test: update card.") + + let card: Card = Fixtures.loadCard(fields: ["id": "foobar"]) card.adapter = MockRestAdapter(body: Mapper().toJSONString(card)!) - let expectation = expectationWithDescription("Card test: update card.") - card.update(["id": "foobar"]).then { (card: Card) -> () in + card.update(updateFields: ["id": "foobar"]).then { (card: Card) -> Void in XCTAssertEqual(card.id, "foobar", "Failed: Wrong card id.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Card test: update card error.") + }) wait() } diff --git a/Tests/Integration/Model/RateTest.swift b/Tests/IntegrationTests/ModelTests/RateTest.swift similarity index 74% rename from Tests/Integration/Model/RateTest.swift rename to Tests/IntegrationTests/ModelTests/RateTest.swift index d262653..e9a0b3d 100644 --- a/Tests/Integration/Model/RateTest.swift +++ b/Tests/IntegrationTests/ModelTests/RateTest.swift @@ -2,11 +2,11 @@ import XCTest import UpholdSdk import ObjectMapper - +/// Rate model tests. class RateTest: XCTestCase { func testRateMapperShouldReturnARate() { - let rate = Mapper().map("{\"ask\":\"1\",\"bid\":\"1\",\"currency\":\"BTC\",\"pair\":\"BTCBTC\"}") + let rate = Mapper().map(JSONString: "{\"ask\":\"1\",\"bid\":\"1\",\"currency\":\"BTC\",\"pair\":\"BTCBTC\"}") XCTAssertEqual(rate!.ask!, "1", "Failed: Ask didn't match.") XCTAssertEqual(rate!.bid!, "1", "Failed: Bid didn't match.") diff --git a/Tests/Integration/Model/ReserveTest.swift b/Tests/IntegrationTests/ModelTests/ReserveTest.swift similarity index 73% rename from Tests/Integration/Model/ReserveTest.swift rename to Tests/IntegrationTests/ModelTests/ReserveTest.swift index cc48479..ce1d9a2 100644 --- a/Tests/Integration/Model/ReserveTest.swift +++ b/Tests/IntegrationTests/ModelTests/ReserveTest.swift @@ -8,7 +8,8 @@ import PromiseKit class ReserveTest: UpholdTestCase { func testGetLedgerShouldReturnTheArrayOfDeposits() { - let expectation = expectationWithDescription("Reserve test: get ledger.") + let testExpectation = expectation(description: "Reserve test: get ledger.") + let json: String = "[{" + "\"type\": \"foo\"," + "\"out\": {" + @@ -37,7 +38,7 @@ class ReserveTest: UpholdTestCase { reserve.adapter = MockRestAdapter(body: json) let paginator: Paginator = reserve.getLedger() - paginator.elements.then({ (deposits: [Deposit]) -> () in + paginator.elements.then(execute: { (deposits: [Deposit]) -> Void in let mockRestAdapter: MockRestAdapter = (reserve.adapter as? MockRestAdapter)! XCTAssertEqual(mockRestAdapter.headers!.count, 1, "Failed: Wrong number of headers.") @@ -56,35 +57,43 @@ class ReserveTest: UpholdTestCase { XCTAssertEqual(deposits[1].transactionId, "foobar", "Failed: TransactionId didn't match.") XCTAssertEqual(deposits[1].type, "bar", "Failed: Deposit type didn't match.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("Reserve test: get ledger error.") }) wait() } func testGetLedgerShouldReturnThePaginatorCount() { - let expectation = expectationWithDescription("Reserve test: get ledger.") + let testExpectation = expectation(description: "Reserve test: get ledger.") + let reserve = UpholdClient().getReserve() reserve.adapter = MockRestAdapter(body: "[{ \"id\": \"foobar\" }, { \"id\": \"foobiz\" }]", headers: ["content-range": "0-2/60"]) - reserve.getLedger().count().then({ (count: Int) -> () in + reserve.getLedger().count().then(execute: { (count: Int) -> Void in XCTAssertEqual(count, 60, "Failed: Wrong paginator count.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("Reserve test: get ledger error.") }) wait() } func testGetLedgerShouldReturnThePaginatorHasNext() { - let expectation = expectationWithDescription("Reserve test: get ledger.") + let testExpectation = expectation(description: "Reserve test: get ledger.") + let reserve = UpholdClient().getReserve() reserve.adapter = MockRestAdapter(body: "[{ \"id\": \"foobar\" }, { \"id\": \"foobiz\" }]", headers: ["content-range": "0-49/51"]) - reserve.getLedger().hasNext().then({ (bool: Bool) -> () in + reserve.getLedger().hasNext().then(execute: { (bool: Bool) -> Void in XCTAssertTrue(bool, "Failed: Wrong paginator hasNext value.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("Reserve test: get ledger error.") }) wait() @@ -95,11 +104,15 @@ class ReserveTest: UpholdTestCase { reserve.adapter = MockRestAdapter(body: "[{ \"id\": \"foobar\" }, { \"id\": \"foobiz\" }]") let paginator: Paginator = reserve.getLedger() - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("Reserve test: get ledger error.") + }) let firstRequestHeaders = (reserve.adapter as? MockRestAdapter)!.headers - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("Reserve test: get ledger error.") + }) let secondRequestHeaders = (reserve.adapter as? MockRestAdapter)!.headers @@ -110,7 +123,8 @@ class ReserveTest: UpholdTestCase { } func testGetStatisticsShouldReturnTheListWithReserveStatistics() { - let expectation = expectationWithDescription("Reserve test.") + let testExpectation = expectation(description: "Reserve test.") + let json: String = "[{" + "\"currency\": \"FOO\"," + "\"values\": [{" + @@ -143,7 +157,7 @@ class ReserveTest: UpholdTestCase { let reserve = UpholdClient().getReserve() reserve.adapter = MockRestAdapter(body: json) - reserve.getStatistics().then { (statistics: [ReserveStatistics]) -> () in + reserve.getStatistics().then { (statistics: [ReserveStatistics]) -> Void in XCTAssertEqual(statistics[0].currency, "FOO", "Failed: Currency didn't match.") XCTAssertEqual(statistics[0].totals!.assets, "foobar", "Failed: Totals assets didn't match.") XCTAssertEqual(statistics[0].totals!.commissions, "foo", "Failed: Totals comissions didn't match.") @@ -163,32 +177,38 @@ class ReserveTest: UpholdTestCase { XCTAssertEqual(statistics[1].values!.first!.liabilities, "buz", "Failed: Values liabilities didn't match.") XCTAssertEqual(statistics[1].values!.first!.rate, "foo", "Failed: Values rate didn't match.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Reserve test error.") + }) wait() } func testGetTransactionsByIdShouldReturnTheTransaction() { - let expectation = expectationWithDescription("Reserve test: get transaction by id.") + let testExpectation = expectation(description: "Reserve test: get transaction by id.") + let reserve = UpholdClient().getReserve() - reserve.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(["transactionId": "foobar"]))!) + reserve.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadTransaction(fields: ["transactionId": "foobar"]))!) - reserve.getTransactionById("foobar").then { (transaction: Transaction) -> () in + reserve.getTransactionById(transactionId: "foobar").then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: TransactionId didn't match.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Reserve test: get transaction by id error.") + }) wait() } func testGetTransactionsShouldReturnTheArrayOfTransactions() { - let expectation = expectationWithDescription("Reserve test: get transactions.") + let testExpectation = expectation(description: "Reserve test: get transactions.") + let reserve = UpholdClient().getReserve() - reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!) + reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!) - reserve.getTransactions().elements.then({ (transactions: [Transaction]) -> () in + reserve.getTransactions().elements.then(execute: { (transactions: [Transaction]) -> Void in let mockRestAdapter: MockRestAdapter = (reserve.adapter as? MockRestAdapter)! XCTAssertEqual(mockRestAdapter.headers!.count, 1, "Failed: Wrong number of headers.") @@ -197,35 +217,43 @@ class ReserveTest: UpholdTestCase { XCTAssertEqual(transactions[0].id, "foobar", "Failed: Wrong transaction object.") XCTAssertEqual(transactions[1].id, "foobiz", "Failed: Wrong transaction object.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("Reserve test: get transaction error.") }) wait() } func testGetTransactionsShouldReturnThePaginatorCount() { - let expectation = expectationWithDescription("Reserve test: get transactions.") + let testExpectation = expectation(description: "Reserve test: get transactions.") + let reserve = UpholdClient().getReserve() - reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!, headers: ["content-range": "0-2/60"]) + reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!, headers: ["content-range": "0-2/60"]) - reserve.getTransactions().count().then({ (count: Int) -> () in + reserve.getTransactions().count().then(execute: { (count: Int) -> Void in XCTAssertEqual(count, 60, "Failed: Wrong paginator count.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("Reserve test: get transactions error.") }) wait() } func testGetTransactionsShouldReturnThePaginatorHasNext() { - let expectation = expectationWithDescription("Reserve test: get transactions.") + let testExpectation = expectation(description: "Reserve test: get transactions.") + let reserve = UpholdClient().getReserve() - reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!, headers: ["content-range": "0-49/51"]) + reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!, headers: ["content-range": "0-49/51"]) - reserve.getTransactions().hasNext().then({ (bool: Bool) -> () in + reserve.getTransactions().hasNext().then(execute: { (bool: Bool) -> Void in XCTAssertTrue(bool, "Failed: Wrong paginator hasNext value.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("Reserve test: get transactions error.") }) wait() @@ -233,14 +261,18 @@ class ReserveTest: UpholdTestCase { func testGetTransactionsShouldReturnThePaginatorNextPage() { let reserve = UpholdClient().getReserve() - reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!) + reserve.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!) let paginator: Paginator = reserve.getTransactions() - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("Reserve test: get next transactions error.") + }) let firstRequestHeaders = (reserve.adapter as? MockRestAdapter)!.headers - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("Reserve test: get next transactions error.") + }) let secondRequestHeaders = (reserve.adapter as? MockRestAdapter)!.headers diff --git a/Tests/Integration/Model/TransactionTest.swift b/Tests/IntegrationTests/ModelTests/TransactionTest.swift similarity index 74% rename from Tests/Integration/Model/TransactionTest.swift rename to Tests/IntegrationTests/ModelTests/TransactionTest.swift index 1a0cebb..2026a33 100644 --- a/Tests/Integration/Model/TransactionTest.swift +++ b/Tests/IntegrationTests/ModelTests/TransactionTest.swift @@ -7,11 +7,12 @@ import PromiseKit class TransactionTest: UpholdTestCase { func testCancelShouldReturnUnexpectedResponseErrorIfAccountIdIsNil() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\", \"type\": \"deposit\"}")! + let testExpectation = expectation(description: "Transaction test: cancel transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\", \"type\": \"deposit\"}")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.cancel().error { (error: ErrorType) -> Void in + transaction.cancel().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -21,18 +22,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Origin accountId is missing from this transaction.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCancelShouldReturnUnexpectedResponseErrorIfCardIdIsNil() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\" }")! + let testExpectation = expectation(description: "Transaction test: cancel transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\" }")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.cancel().error { (error: ErrorType) -> Void in + transaction.cancel().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -42,18 +44,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Origin cardId is missing from this transaction.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCancelShouldReturnUnexpectedResponseErrorIfDestinationCardIdIsNil() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\", \"type\": \"deposit\", \"origin\": { \"AccountId\": \"fiz\"}}")! + let testExpectation = expectation(description: "Transaction test: cancel transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\", \"type\": \"deposit\", \"origin\": { \"AccountId\": \"fiz\"}}")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.cancel().error { (error: ErrorType) -> Void in + transaction.cancel().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -63,18 +66,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Destination cardId is missing from this transaction.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCancelShouldReturnUnexpectedResponseErrorIfTransactionIdIsNil() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction: Transaction = Mapper().map("{}")! + let testExpectation = expectation(description: "Transaction test: cancel transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{}")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.cancel().error { (error: ErrorType) -> Void in + transaction.cancel().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -84,18 +88,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Transaction id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCancelShouldReturnUnexpectedResponseErrorIfStatusIsNil() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\", \"origin\": { \"CardId\": \"fiz\"} }")! + let testExpectation = expectation(description: "Transaction test: cancel transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\", \"origin\": { \"CardId\": \"fiz\"} }")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.cancel().error { (error: ErrorType) -> Void in + transaction.cancel().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -105,18 +110,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Transaction status should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCancelShouldReturnLogicErrorIfStatusIsPending() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction = Fixtures.loadTransaction(["transactionStatus": "pending"]) + let testExpectation = expectation(description:"Transaction test: cancel transaction.") + + let transaction = Fixtures.loadTransaction(fields: ["transactionStatus": "pending"]) transaction.adapter = MockRestAdapter(body: "foobar") - transaction.cancel().error { (error: ErrorType) -> Void in + transaction.cancel().catch(execute: { (error: Error) in guard let error = error as? LogicError else { XCTFail("Error should be LogicError.") @@ -126,18 +132,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Unable to cancel uncommited transaction.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCancelShouldReturnLogicErrorIfStatusIsNotWaiting() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction = Fixtures.loadTransaction(["transactionStatus": "foobar"]) + let testExpectation = expectation(description:"Transaction test: cancel transaction.") + + let transaction = Fixtures.loadTransaction(fields: ["transactionStatus": "foobar"]) transaction.adapter = MockRestAdapter(body: "foobar") - transaction.cancel().error { (error: ErrorType) -> Void in + transaction.cancel().catch(execute: { (error: Error) in guard let error = error as? LogicError else { XCTFail("Error should be LogicError.") @@ -147,88 +154,104 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "This transaction cannot be cancelled, because the current status is foobar.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCancelShouldReturnTheCanceledTransaction() { - let expectation = expectationWithDescription("Transaction test: cancel transaction.") - let transaction: Transaction = Fixtures.loadTransaction(["transactionId": "foobar", "transactionStatus": "waiting"]) + let testExpectation = expectation(description:"Transaction test: cancel transaction.") + + let transaction: Transaction = Fixtures.loadTransaction(fields: ["transactionId": "foobar", "transactionStatus": "waiting"]) transaction.adapter = MockRestAdapter(body: Mapper().toJSONString(transaction)!) - transaction.cancel().then { (transaction: Transaction) -> () in + transaction.cancel().then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Transaction test: cancel transaction error.") + }) wait() } func testCommitShouldReturnTheTransaction() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Fixtures.loadTransaction(["transactionId": "foobar", "transactionStatus": "pending"]) + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Fixtures.loadTransaction(fields: ["transactionId": "foobar", "transactionStatus": "pending"]) transaction.adapter = MockRestAdapter(body: Mapper().toJSONString(transaction)!) - transaction.commit().then { (transaction: Transaction) -> () in + transaction.commit().then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Transaction test: commit transaction error.") + }) wait() } func testCommitWithOTPShouldReturnTheTransaction() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Fixtures.loadTransaction(["transactionId": "foobar", "transactionStatus": "pending"]) + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Fixtures.loadTransaction(fields: ["transactionId": "foobar", "transactionStatus": "pending"]) transaction.adapter = MockRestAdapter(body: Mapper().toJSONString(transaction)!) - transaction.commit("otp").then { (transaction: Transaction) -> () in + transaction.commit(otp: "otp").then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction transfer error.") + }) wait() } func testCommitWithTransactionCommitRequestAndOTPShouldReturnTheTransaction() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Fixtures.loadTransaction(["transactionId": "foobar", "transactionStatus": "pending"]) + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Fixtures.loadTransaction(fields: ["transactionId": "foobar", "transactionStatus": "pending"]) transaction.adapter = MockRestAdapter(body: Mapper().toJSONString(transaction)!) - transaction.commit("otp", transactionCommit: TransactionCommitRequest(message: "foobar")).then { (transaction: Transaction) -> () in + transaction.commit(otp: "otp", transactionCommit: TransactionCommitRequest(message: "foobar")).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction transfer error.") + }) wait() } func testCommitWithTransactionCommitRequestShouldReturnTheTransaction() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Fixtures.loadTransaction(["transactionId": "foobar", "transactionStatus": "pending"]) + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Fixtures.loadTransaction(fields: ["transactionId": "foobar", "transactionStatus": "pending"]) transaction.adapter = MockRestAdapter(body: Mapper().toJSONString(transaction)!) - transaction.commit(TransactionCommitRequest(message: "foobar")).then { (transaction: Transaction) -> () in + transaction.commit(transactionCommit: TransactionCommitRequest(message: "foobar")).then { (transaction: Transaction) -> Void in XCTAssertEqual(transaction.id, "foobar", "Failed: Wrong transaction object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create transaction transfer error.") + }) wait() } func testCommitShouldReturnUnexpectedResponseErrorIfAccountIdIsNil() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\", \"type\": \"deposit\"}")! + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\", \"type\": \"deposit\"}")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.commit(TransactionCommitRequest(message: "foobar")).error { (error: ErrorType) -> Void in + transaction.commit(transactionCommit: TransactionCommitRequest(message: "foobar")).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -238,18 +261,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Origin accountId is missing from this transaction.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCommitShouldReturnUnexpectedResponseErrorIfCardIdIsNil() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\" }")! + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\" }")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.commit(TransactionCommitRequest(message: "foobar")).error { (error: ErrorType) -> Void in + transaction.commit(transactionCommit: TransactionCommitRequest(message: "foobar")).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -259,18 +283,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Origin cardId is missing from this transaction.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCommitShouldReturnUnexpectedResponseErrorIfDestinationCardIdIsNil() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\", \"type\": \"deposit\", \"origin\": { \"AccountId\": \"fiz\"}}")! + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\", \"type\": \"deposit\", \"origin\": { \"AccountId\": \"fiz\"}}")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.commit(TransactionCommitRequest(message: "foobar")).error { (error: ErrorType) -> Void in + transaction.commit(transactionCommit: TransactionCommitRequest(message: "foobar")).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -280,18 +305,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Destination cardId is missing from this transaction.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCommitShouldReturnUnexpectedResponseErrorIfTransactionIdIsNil() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Mapper().map("{}")! + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{}")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.commit(TransactionCommitRequest(message: "foobar")).error { (error: ErrorType) -> Void in + transaction.commit(transactionCommit: TransactionCommitRequest(message: "foobar")).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -301,18 +327,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Transaction id should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCommitShouldReturnUnexpectedResponseErrorIfStatusIsNil() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction: Transaction = Mapper().map("{ \"id\": \"foobar\", \"origin\": { \"CardId\": \"fiz\"} }")! + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction: Transaction = Mapper().map(JSONString: "{ \"id\": \"foobar\", \"origin\": { \"CardId\": \"fiz\"} }")! transaction.adapter = MockRestAdapter(body: "foobar") - transaction.commit(TransactionCommitRequest(message: "foobar")).error { (error: ErrorType) -> Void in + transaction.commit(transactionCommit: TransactionCommitRequest(message: "foobar")).catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -322,18 +349,19 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Transaction status should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testCommitShouldReturnLogicErrorIfStatusIsNotPending() { - let expectation = expectationWithDescription("Transaction test: commit transaction.") - let transaction = Fixtures.loadTransaction(["transactionStatus": "foobar"]) + let testExpectation = expectation(description:"Transaction test: commit transaction.") + + let transaction = Fixtures.loadTransaction(fields: ["transactionStatus": "foobar"]) transaction.adapter = MockRestAdapter(body: "foobar") - transaction.commit(TransactionCommitRequest(message: "foobar")).error { (error: ErrorType) -> Void in + transaction.commit(transactionCommit: TransactionCommitRequest(message: "foobar")).catch(execute: { (error: Error) in guard let error = error as? LogicError else { XCTFail("Error should be LogicError.") @@ -343,8 +371,8 @@ class TransactionTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "This transaction cannot be committed, because the current status is foobar.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } @@ -434,7 +462,7 @@ class TransactionTest: UpholdTestCase { "\"percentage\": \"2.75\"" + "}]" + "}" - let transaction = Mapper().map(json) + let transaction = Mapper().map(JSONString: json) XCTAssertEqual(transaction!.id!, "foobar", "Failed: Transaction id didn't match.") XCTAssertEqual(transaction!.createdAt!, "fuz", "Failed: Transaction createdAt didn't match.") diff --git a/Tests/Integration/Model/UserTest.swift b/Tests/IntegrationTests/ModelTests/UserTest.swift similarity index 73% rename from Tests/Integration/Model/UserTest.swift rename to Tests/IntegrationTests/ModelTests/UserTest.swift index 5d38efd..a79cf99 100644 --- a/Tests/Integration/Model/UserTest.swift +++ b/Tests/IntegrationTests/ModelTests/UserTest.swift @@ -7,68 +7,78 @@ import PromiseKit class UserTest: UpholdTestCase { func testCreateCardShouldReturnTheCard() { - let expectation = expectationWithDescription("User test: create card.") + let testExpectation = expectation(description: "User test: create card.") + let user: User = Fixtures.loadUser() - user.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadCard(["id": "foobar", "currency": "foo", "label": "BTC"]))!) + user.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadCard(fields: ["id": "foobar", "currency": "foo", "label": "BTC"]))!) - user.createCard(CardRequest(currency: "foo", label: "BTC")).then { (card: Card) -> () in + user.createCard(cardRequest: CardRequest(currency: "foo", label: "BTC")).then { (card: Card) -> Void in XCTAssertEqual(card.currency, "foo", "Failed: Wrong card currency.") XCTAssertEqual(card.id, "foobar", "Failed: Wrong card id.") XCTAssertEqual(card.label, "BTC", "Failed: Wrong card label.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create card error.") + }) wait() } func testCreateCardWithSettingsShouldReturnTheCard() { + let testExpectation = expectation(description: "User test: create card.") + let cardSettings: CardSettings = CardSettings(position: 1, starred: true) - let expectation = expectationWithDescription("User test: create card.") let user: User = Fixtures.loadUser() - user.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadCard(["id": "foobar"]))!) + user.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadCard(fields: ["id": "foobar"]))!) - user.createCard(CardRequest(currency: "foo", label: "BTC", settings: cardSettings)).then { (card: Card) -> () in + user.createCard(cardRequest: CardRequest(currency: "foo", label: "BTC", settings: cardSettings)).then { (card: Card) -> Void in XCTAssertEqual(card.id, "foobar", "Failed: Wrong card id.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: create card error.") + }) wait() } func testGetAccountByIdShouldReturnTheAccount() { - let account: Account = Fixtures.loadAccount(["id": "foobar"]) - let expectation = expectationWithDescription("User test: get account by id.") + let testExpectation = expectation(description: "User test: get account by id.") + + let account: Account = Fixtures.loadAccount(fields: ["id": "foobar"]) let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: Mapper().toJSONString(account)!) - user.getAccountById("foobar").then { (account: Account) -> () in + user.getAccountById(accountId: "foobar").then { (account: Account) -> Void in XCTAssertEqual(account.id, "foobar", "Failed: Wrong account object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get account by id error.") + }) wait() } func testCreateDocumentShouldReturnTheDocument() { - let expectation = expectationWithDescription("User test: create document.") + let testExpectation = expectation(description: "User test: create document.") let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: Mapper().toJSONString(Document(type: "foo", value: "bar"))!) - user.createDocument(Document(type: "foo", value: "bar")).then { (document: Document) -> () in + _ = user.createDocument(document: Document(type: "foo", value: "bar")).then { (document: Document) -> () in XCTAssertEqual(document.type, "foo", "Failed: Wrong card id.") XCTAssertEqual(document.value, "bar", "Failed: Wrong card id.") - expectation.fulfill() + testExpectation.fulfill() } wait() } func testGetAccountsShouldReturnTheArrayOfAccounts() { - let expectation = expectationWithDescription("User test: get accounts.") + let testExpectation = expectation(description: "User test: get accounts.") + let json: String = "[{" + "\"currency\": \"EUR\"," + "\"id\": \"foo\"," + @@ -86,7 +96,7 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getAccounts().then { (accounts: [Account]) -> () in + user.getAccounts().then { (accounts: [Account]) -> Void in XCTAssertEqual(accounts.count, 2, "Failed: Wrong number of accounts.") XCTAssertEqual(accounts[0].currency, "EUR", "Failed: Wrong account object.") XCTAssertEqual(accounts[0].id, "foo", "Failed: Wrong account object.") @@ -99,14 +109,17 @@ class UserTest: UpholdTestCase { XCTAssertEqual(accounts[1].status, "foobiz", "Failed: Wrong account object.") XCTAssertEqual(accounts[1].type, "biz", "Failed: Wrong account object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get accounts error.") + }) wait() } func testGetBalancesByCurrencyShouldReturnTheCurrencyBalance() { - let expectation = expectationWithDescription("User test: get balances by currency.") + let testExpectation = expectation(description: "User test: get balances by currency.") + let json: String = "{" + "\"balances\": {" + "\"total\": \"1083.77\"," + @@ -135,20 +148,23 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getBalanceByCurrency("EUR").then { (currency: Currency) -> () in + user.getBalanceByCurrency(currency: "EUR").then { (currency: Currency) -> Void in XCTAssertEqual(currency.amount, "75.01", "Failed: Wrong currency amount.") XCTAssertEqual(currency.balance, "58.05", "Failed: Wrong currency balance.") XCTAssertEqual(currency.currency, "EUR", "Failed: Wrong currency.") XCTAssertEqual(currency.rate, "1.29220", "Failed: Wrong currency.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get balances by currency error.") + }) wait() } func testGetBalancesByCurrencyShouldReturnCurrencyDoesNotExistError() { - let expectation = expectationWithDescription("User test: get balances by currency.") + let testExpectation = expectation(description: "User test: get balances by currency.") + let json: String = "{" + "\"balances\": {" + "\"total\": \"1083.77\"," + @@ -171,7 +187,7 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getBalanceByCurrency("USD").error { (error: ErrorType) -> Void in + user.getBalanceByCurrency(currency: "USD").catch(execute: { (error: Error) in guard let error = error as? LogicError else { XCTFail("Error should be LogicError.") @@ -181,18 +197,19 @@ class UserTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "Currency does not exist.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetBalancesByCurrencyShouldReturnEmptyBalancesError() { - let expectation = expectationWithDescription("User test: get balances by currency.") + let testExpectation = expectation(description: "User test: get balances by currency.") + let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: "{}") - user.getBalanceByCurrency("EUR").error { (error: ErrorType) -> Void in + user.getBalanceByCurrency(currency: "EUR").catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -202,18 +219,19 @@ class UserTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: HTTP status code should be nil.") XCTAssertEqual(error.description, "Balances should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetBalancesByCurrencyShouldReturnEmptyCurrenciesError() { - let expectation = expectationWithDescription("User test: get balances by currency.") + let testExpectation = expectation(description: "User test: get balances by currency.") + let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: "{\"balances\": {} }") - user.getBalanceByCurrency("EUR").error { (error: ErrorType) -> Void in + user.getBalanceByCurrency(currency: "EUR").catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -223,14 +241,15 @@ class UserTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: HTTP status code should be nil.") XCTAssertEqual(error.description, "Currencies should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetBalancesShouldReturnTheArrayOfBalances() { - let expectation = expectationWithDescription("User test: get balances.") + let testExpectation = expectation(description: "User test: get balances.") + let json: String = "{" + "\"balances\": {" + "\"total\": \"1083.77\"," + @@ -250,24 +269,27 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getBalances().then { (currencies: [Currency]) -> () in + user.getBalances().then { (currencies: [Currency]) -> Void in XCTAssertEqual(currencies.count, 3, "Failed: Wrong number of currencies.") XCTAssertEqual(currencies[0].amount, "2.45", "Failed: Wrong currency amount.") XCTAssertEqual(currencies[1].amount, "6.98", "Failed: Wrong currency amount.") XCTAssertEqual(currencies[2].amount, "75.01", "Failed: Wrong currency amount.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get balances error.") + }) wait() } func testGetBalancesShouldReturnEmptyBalancesError() { - let expectation = expectationWithDescription("User test: get balances by currency.") + let testExpectation = expectation(description: "User test: get balances by currency.") + let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: "{}") - user.getBalances().error { (error: ErrorType) -> Void in + user.getBalances().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -277,18 +299,19 @@ class UserTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: HTTP status code should be nil.") XCTAssertEqual(error.description, "Balances should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetBalancesShouldReturnEmptyCurrenciesError() { - let expectation = expectationWithDescription("User test: get balances by currency.") + let testExpectation = expectation(description: "User test: get balances by currency.") + let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: "{\"balances\": {} }") - user.getBalances().error { (error: ErrorType) -> Void in + user.getBalances().catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -298,37 +321,41 @@ class UserTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: HTTP status code should be nil.") XCTAssertEqual(error.description, "Currencies should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetCardsByCurrencyShouldReturnTheArrayOfCardsWithCurrency() { - let cards: [Card] = [Fixtures.loadCard(["id": "foobar", "currency": "USD"]), Fixtures.loadCard(["id": "foobiz", "currency": "BTC"]), Fixtures.loadCard(["id": "fuzbuz", "currency": "BTC"])] - let expectation = expectationWithDescription("User test: get cards by currency.") + let testExpectation = expectation(description: "User test: get cards by currency.") + + let cards: [Card] = [Fixtures.loadCard(fields: ["id": "foobar", "currency": "USD"]), Fixtures.loadCard(fields: ["id": "foobiz", "currency": "BTC"]), Fixtures.loadCard(fields: ["id": "fuzbuz", "currency": "BTC"])] let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: Mapper().toJSONString(cards)!) - user.getCardsByCurrency("BTC").then { (cards: [Card]) -> () in + user.getCardsByCurrency(currency: "BTC").then { (cards: [Card]) -> Void in XCTAssertEqual(cards.count, 2, "Failed: Wrong number of card objects.") XCTAssertEqual(cards[0].id, "foobiz", "Failed: Wrong card object.") XCTAssertEqual(cards[0].currency, "BTC", "Failed: Wrong card currency.") XCTAssertEqual(cards[1].id, "fuzbuz", "Failed: Wrong card object.") XCTAssertEqual(cards[1].currency, "BTC", "Failed: Wrong card currency.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get cards by currency error.") + }) wait() } func testGetCardsByCurrencyShouldReturnUnmatchedCurrencyError() { - let expectation = expectationWithDescription("User test: get balances by currency.") + let testExpectation = expectation(description: "User test: get balances by currency.") + let user: User = Fixtures.loadUser() - user.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadCard(["id": "foobar", "currency": "BTC"]))!) + user.adapter = MockRestAdapter(body: Mapper().toJSONString(Fixtures.loadCard(fields: ["id": "foobar", "currency": "BTC"]))!) - user.getCardsByCurrency("USD").error { (error: ErrorType) -> Void in + user.getCardsByCurrency(currency: "USD").catch(execute: { (error: Error) in guard let error = error as? LogicError else { XCTFail("Error should be LogicError.") @@ -338,45 +365,52 @@ class UserTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: Wrong code.") XCTAssertEqual(error.description, "There are no cards in the given currency.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetCardByIdShouldReturnTheCard() { - let card: Card = Fixtures.loadCard(["id": "foobar"]) - let expectation = expectationWithDescription("User test: get card by id.") + let testExpectation = expectation(description: "User test: get card by id.") + + let card: Card = Fixtures.loadCard(fields: ["id": "foobar"]) let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: Mapper().toJSONString(card)!) - user.getCardById("foobar").then { (card: Card) -> () in + user.getCardById(cardId: "foobar").then { (card: Card) -> Void in XCTAssertEqual(card.id, "foobar", "Failed: Wrong card object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get card by id error.") + }) wait() } func testGetCardsShouldReturnTheArrayOfCards() { - let cards: [Card] = [Fixtures.loadCard(["id": "foo"]), Fixtures.loadCard(["id": "bar"])] - let expectation = expectationWithDescription("User test: get cards.") + let testExpectation = expectation(description: "User test: get cards.") + + let cards: [Card] = [Fixtures.loadCard(fields: ["id": "foo"]), Fixtures.loadCard(fields: ["id": "bar"])] let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: Mapper().toJSONString(cards)!) - user.getCards().then { (cards: [Card]) -> () in + user.getCards().then { (cards: [Card]) -> Void in XCTAssertEqual(cards[0].id, "foo", "Failed: Wrong card object.") XCTAssertEqual(cards[1].id, "bar", "Failed: Wrong card object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get cards error.") + }) wait() } func testGetContactsShouldReturnTheListOfContacts() { - let expectation = expectationWithDescription("User test: get contacts.") + let testExpectation = expectation(description: "User test: get contacts.") + let json: String = "[{" + "\"id\": \"foobar\"," + "\"firstName\": \"Foo\"," + @@ -401,7 +435,7 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getContacts().then { (contact: [Contact]) -> () in + user.getContacts().then { (contact: [Contact]) -> Void in XCTAssertEqual(contact.count, 2, "Failed: Wrong number of contacts objects.") XCTAssertEqual(contact[0].addresses!.count, 1, "Failed: Wrong number of addresses.") XCTAssertEqual(contact[0].addresses![0], "FooBar FooBiz", "Failed: Wrong contact object.") @@ -422,14 +456,16 @@ class UserTest: UpholdTestCase { XCTAssertEqual(contact[1].lastName, "Buz", "Failed: Wrong contact object.") XCTAssertEqual(contact[1].name, "Fuz Buz", "Failed: Wrong contact object.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get contacts error.") + }) wait() } func testGetDocumentsShouldReturnTheListOfDocuments() { - let expectation = expectationWithDescription("User test: get documents.") + let testExpectation = expectation(description: "User test: get documents.") let json: String = "[{" + "\"type\": \"foo\"," + "\"value\": \"bar\"" + @@ -437,18 +473,19 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getDocuments().then { (documents: [Document]) -> () in + _ = user.getDocuments().then { (documents: [Document]) -> () in XCTAssertEqual(documents.count, 1, "Failed: Wrong number of documents objects.") XCTAssertEqual(documents[0].type, "foo", "Failed: Wrong document type field.") XCTAssertEqual(documents[0].value, "bar", "Failed: Wrong document value.") - expectation.fulfill() + testExpectation.fulfill() } wait() } func testGetPhonesShouldReturnTheListOfPhones() { - let expectation = expectationWithDescription("User test: get phones.") + let testExpectation = expectation(description: "User test: get phones.") + let json: String = "[{" + "\"id\": \"foobar\"," + "\"verified\": true," + @@ -458,21 +495,24 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getPhones().then { (phones: [Phone]) -> () in + user.getPhones().then { (phones: [Phone]) -> Void in XCTAssertEqual(phones.count, 1, "Failed: Wrong number of phone objects.") XCTAssertEqual(phones[0].e164Masked, "+XXXXXXXXX04", "Failed: Wrong phone e164Masked field.") XCTAssertEqual(phones[0].id, "foobar", "Failed: Wrong phone id.") XCTAssertTrue(phones[0].primary!, "Failed: Wrong phone primary field.") XCTAssertTrue(phones[0].verified!, "Failed: Wrong phone verified field.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get phones error.") + }) wait() } func testGetTotalBalancesShouldReturnTheTotalBalance() { - let expectation = expectationWithDescription("User test: get total balances.") + let testExpectation = expectation(description: "User test: get total balances.") + let json: String = "{" + "\"balances\": {" + "\"total\": \"1083.77\"," + @@ -495,7 +535,7 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - user.getTotalBalances().then { (balances: UserBalance) -> () in + user.getTotalBalances().then { (balances: UserBalance) -> Void in guard let currencies = balances.currencies else { XCTFail("Currencies should not be nil.") @@ -513,19 +553,22 @@ class UserTest: UpholdTestCase { XCTAssertEqual(currencies["EUR"]!.rate, "1.29220", "Failed: Wrong currency rate.") XCTAssertEqual(balances.total, "1083.77", "Failed: Wrong balance total.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: get total balances error.") + }) wait() } func testGetTotalBalancesShouldReturnEmptyBalancesError() { - let expectation = expectationWithDescription("User test: get total balances.") + let testExpectation = expectation(description: "User test: get total balances.") + let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: "{}") let promise: Promise = user.getTotalBalances() - promise.error { (error: ErrorType) -> Void in + promise.catch(execute: { (error: Error) in guard let error = error as? UnexpectedResponseError else { XCTFail("Error should be UnexpectedResponseError.") @@ -535,18 +578,19 @@ class UserTest: UpholdTestCase { XCTAssertNil(error.code, "Failed: HTTP status code should be nil.") XCTAssertEqual(error.description, "Balances should not be nil.", "Failed: Wrong message.") - expectation.fulfill() - } + testExpectation.fulfill() + }) wait() } func testGetTransactionsShouldReturnTheArrayOfTransactions() { - let expectation = expectationWithDescription("User test: get transactions.") + let testExpectation = expectation(description: "User test: get transactions.") + let user: User = Fixtures.loadUser() - user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!) + user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!) - user.getUserTransactions().elements.then({ (transactions: [Transaction]) -> () in + user.getUserTransactions().elements.then(execute: { (transactions: [Transaction]) -> Void in let mockRestAdapter: MockRestAdapter = (user.adapter as? MockRestAdapter)! XCTAssertEqual(mockRestAdapter.headers!.count, 1, "Failed: Wrong number of headers.") @@ -555,35 +599,43 @@ class UserTest: UpholdTestCase { XCTAssertEqual(transactions[0].id, "foobar", "Failed: Wrong transaction object.") XCTAssertEqual(transactions[1].id, "foobiz", "Failed: Wrong transaction object.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("User test: get transactions error.") }) wait() } func testGetTransactionsShouldReturnThePaginatorCount() { - let expectation = expectationWithDescription("User test: get transactions.") + let testExpectation = expectation(description: "User test: get transactions.") + let user: User = Fixtures.loadUser() - user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!, headers: ["content-range": "0-2/60"]) + user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!, headers: ["content-range": "0-2/60"]) - user.getUserTransactions().count().then({ (count: Int) -> () in + user.getUserTransactions().count().then(execute: { (count: Int) -> Void in XCTAssertEqual(count, 60, "Failed: Wrong paginator count.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("User test: get transactions error.") }) wait() } func testGetTransactionsShouldReturnThePaginatorHasNext() { - let expectation = expectationWithDescription("User test: get transactions.") + let testExpectation = expectation(description: "User test: get transactions.") + let user: User = Fixtures.loadUser() - user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!, headers: ["content-range": "0-49/51"]) + user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!, headers: ["content-range": "0-49/51"]) - user.getUserTransactions().hasNext().then({ (bool: Bool) -> () in + user.getUserTransactions().hasNext().then(execute: { (bool: Bool) -> Void in XCTAssertTrue(bool, "Failed: Wrong paginator hasNext value.") - expectation.fulfill() + testExpectation.fulfill() + }).catch(execute: { (_: Error) in + XCTFail("User test: get transactions error.") }) wait() @@ -591,14 +643,18 @@ class UserTest: UpholdTestCase { func testGetTransactionsShouldReturnThePaginatorNextPage() { let user: User = Fixtures.loadUser() - user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(["transactionId": "foobar"]), Fixtures.loadTransaction(["transactionId": "foobiz"])])!) + user.adapter = MockRestAdapter(body: Mapper().toJSONString([Fixtures.loadTransaction(fields: ["transactionId": "foobar"]), Fixtures.loadTransaction(fields: ["transactionId": "foobiz"])])!) let paginator: Paginator = user.getUserTransactions() - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("User test: get next transactions error.") + }) let firstRequestHeaders = (user.adapter as? MockRestAdapter)!.headers - paginator.getNext() + paginator.getNext().catch(execute: { (_: Error) in + XCTFail("User test: get next transactions error.") + }) let secondRequestHeaders = (user.adapter as? MockRestAdapter)!.headers @@ -609,15 +665,18 @@ class UserTest: UpholdTestCase { } func testUpdateShouldReturnTheUser() { - let expectation = expectationWithDescription("User test: update user.") - let user: User = Fixtures.loadUser(["username": "foobar"]) + let testExpectation = expectation(description: "User test: update user.") + + let user: User = Fixtures.loadUser(fields: ["username": "foobar"]) user.adapter = MockRestAdapter(body: Mapper().toJSONString(user)!) - user.update(["username": "foobar"]).then { (user: User) -> () in + user.update(updateFields: ["username": "foobar"]).then { (user: User) -> Void in XCTAssertEqual(user.username, "foobar", "Failed: Wrong username.") - expectation.fulfill() - } + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("User test: update user error.") + }) wait() } @@ -670,7 +729,7 @@ class UserTest: UpholdTestCase { "}" + "}" + "}" - let user = Mapper().map(json) + let user = Mapper().map(JSONString: json) XCTAssertEqual(user!.country!, "BAR", "Failed: User country didn't match.") XCTAssertEqual(user!.currencies!.count, 1, "Failed: User currencies didn't match.") diff --git a/Tests/IntegrationTests/PaginatorTests/PaginatorTest.swift b/Tests/IntegrationTests/PaginatorTests/PaginatorTest.swift new file mode 100644 index 0000000..9cec4bf --- /dev/null +++ b/Tests/IntegrationTests/PaginatorTests/PaginatorTest.swift @@ -0,0 +1,86 @@ +import XCTest +import PromiseKit +@testable import UpholdSdk + +/// Paginator integration tests. +class PaginatorTest: UpholdTestCase { + + let paginator: Paginator = Paginator(countClosure: { () -> Promise in + return Promise { fulfill, _ in + fulfill(10) + } + }, + elements: Promise { fulfill, _ in + fulfill([AnyObject]()) + }, + hasNextPageClosure: { (_) -> Promise in + return Promise { fulfill, _ in + fulfill(true) + } + }, + nextPageClosure: { (_) -> Promise<[AnyObject]> in + return Promise { fulfill, _ in + let arrayObject = ["foo", "bar"] + fulfill(arrayObject as [AnyObject]) + } + }) + + func testCount() { + let testExpectation = expectation(description: "Paginator test.") + + paginator.count().then { (count: Int) -> Void in + XCTAssertEqual(count, 10, "Failed: Wrong object.") + + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Paginator test error.") + }) + + wait() + } + + func testGetNext() { + let testExpectation = expectation(description: "Paginator test.") + + paginator.getNext().then { (objects: [AnyObject]) -> Void in + XCTAssertEqual(objects[0] as? String, "foo", "Failed: Wrong object.") + XCTAssertEqual(objects[1] as? String, "bar", "Failed: Wrong object.") + + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Paginator test error.") + }) + + wait() + } + + func testGetNextPage() { + let testExpectation = expectation(description: "Paginator test.") + + paginator.nextPageClosure("foobar").then { (objects: [AnyObject]) -> Void in + XCTAssertEqual(objects[0] as? String, "foo", "Failed: Wrong object.") + XCTAssertEqual(objects[1] as? String, "bar", "Failed: Wrong object.") + + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Paginator test error.") + }) + + wait() + } + + func testHasNextPage() { + let testExpectation = expectation(description: "Paginator test.") + + paginator.hasNextPageClosure(1).then { (hasNext: Bool) -> Void in + XCTAssertTrue(hasNext, "Failed: Wrong object.") + + testExpectation.fulfill() + }.catch(execute: { (_: Error) in + XCTFail("Paginator test error.") + }) + + wait() + } + +} diff --git a/Tests/Integration/Service/AccountsServiceTest.swift b/Tests/IntegrationTests/ServiceTests/AccountsServiceTest.swift similarity index 90% rename from Tests/Integration/Service/AccountsServiceTest.swift rename to Tests/IntegrationTests/ServiceTests/AccountsServiceTest.swift index 2d3a9f0..e96eae8 100644 --- a/Tests/Integration/Service/AccountsServiceTest.swift +++ b/Tests/IntegrationTests/ServiceTests/AccountsServiceTest.swift @@ -6,7 +6,7 @@ import XCTest class AccountServiceTest: XCTestCase { func testGetUserAccountByIdShouldReturnTheRequest() { - let request = AccountsService.getUserAccountById("foo") + let request = AccountsService.getUserAccountById(accountId: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/accounts/foo", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") diff --git a/Tests/Integration/Service/OAuth2ServiceTest.swift b/Tests/IntegrationTests/ServiceTests/OAuth2ServiceTest.swift similarity index 70% rename from Tests/Integration/Service/OAuth2ServiceTest.swift rename to Tests/IntegrationTests/ServiceTests/OAuth2ServiceTest.swift index c15571f..6912619 100644 --- a/Tests/Integration/Service/OAuth2ServiceTest.swift +++ b/Tests/IntegrationTests/ServiceTests/OAuth2ServiceTest.swift @@ -6,9 +6,9 @@ import XCTest class OAuth2ServiceTest: XCTestCase { func testRequestTokenShouldReturnTheToken() { - let request = OAuth2Service.requestToken("foo", clientSecret: "bar", code: "foobar", grantType: "foobiz") - let loginData: NSData = "foo:bar".dataUsingEncoding(NSUTF8StringEncoding)! - let base64LoginString = loginData.base64EncodedStringWithOptions([]) + let request = OAuth2Service.requestToken(clientId: "foo", clientSecret: "bar", code: "foobar", grantType: "foobiz") + let loginData: Data = "foo:bar".data(using: String.Encoding.utf8)! + let base64LoginString = loginData.base64EncodedString(options: []) XCTAssertEqual(request.url, String(format: "%@/oauth2/token", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.headers["authorization"], String(format: "Basic %@", base64LoginString), "Failed: Wrong method.") diff --git a/Tests/Integration/Service/ReserveServiceTest.swift b/Tests/IntegrationTests/ServiceTests/ReserveServiceTest.swift similarity index 88% rename from Tests/Integration/Service/ReserveServiceTest.swift rename to Tests/IntegrationTests/ServiceTests/ReserveServiceTest.swift index 1ef094f..cfa3950 100644 --- a/Tests/Integration/Service/ReserveServiceTest.swift +++ b/Tests/IntegrationTests/ServiceTests/ReserveServiceTest.swift @@ -6,7 +6,7 @@ import XCTest class ReserveServiceTest: XCTestCase { func testGetLedgerShouldReturnTheRequest() { - let request = ReserveService.getLedger("foo") + let request = ReserveService.getLedger(range: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/reserve/ledger", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") @@ -15,14 +15,14 @@ class ReserveServiceTest: XCTestCase { } func testGetReserveTransactionByIdShouldReturnTheRequest() { - let request = ReserveService.getReserveTransactionById("foo") + let request = ReserveService.getReserveTransactionById(transactionId: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/reserve/transactions/foo", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") } func testGetReserveTransactionsShouldReturnTheRequest() { - let request = ReserveService.getReserveTransactions("foo") + let request = ReserveService.getReserveTransactions(range: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/reserve/transactions", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") diff --git a/Tests/Integration/Service/TickerServiceTest.swift b/Tests/IntegrationTests/ServiceTests/TickerServiceTest.swift similarity index 90% rename from Tests/Integration/Service/TickerServiceTest.swift rename to Tests/IntegrationTests/ServiceTests/TickerServiceTest.swift index 035c7c1..1cae9ee 100644 --- a/Tests/Integration/Service/TickerServiceTest.swift +++ b/Tests/IntegrationTests/ServiceTests/TickerServiceTest.swift @@ -13,7 +13,7 @@ class TickerServiceTest: XCTestCase { } func testGetAllTickersByCurrencyShouldReturnTheRequest() { - let request = TickerService.getAllTickersByCurrency("foo") + let request = TickerService.getAllTickersByCurrency(currency: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/ticker/foo", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") diff --git a/Tests/Integration/Service/UserCardServiceTest.swift b/Tests/IntegrationTests/ServiceTests/UserCardServiceTest.swift similarity index 81% rename from Tests/Integration/Service/UserCardServiceTest.swift rename to Tests/IntegrationTests/ServiceTests/UserCardServiceTest.swift index 761b3ec..f8ddb47 100644 --- a/Tests/Integration/Service/UserCardServiceTest.swift +++ b/Tests/IntegrationTests/ServiceTests/UserCardServiceTest.swift @@ -6,14 +6,14 @@ import XCTest class UserCardServiceTest: XCTestCase { func testCancelTransactionShouldReturnTheRequest() { - let request = UserCardService.cancelTransaction("bar", transactionId: "foo") + let request = UserCardService.cancelTransaction(cardId: "bar", transactionId: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar/transactions/foo/cancel", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "POST", "Failed: Wrong method.") } func testCreateAddressShouldReturnTheRequest() { - let request = UserCardService.createCardAddress("bar", addressRequest: "foo") + let request = UserCardService.createCardAddress(cardId: "bar", addressRequest: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar/addresses", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "POST", "Failed: Wrong method.") @@ -21,7 +21,7 @@ class UserCardServiceTest: XCTestCase { } func testConfirmTransactionShouldReturnTheRequest() { - let request = UserCardService.confirmTransaction("bar", otp: nil, transactionId: "foo", transactionCommitRequest: "foobar") + let request = UserCardService.confirmTransaction(cardId: "bar", otp: nil, transactionId: "foo", transactionCommitRequest: "foobar") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar/transactions/foo/commit", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "POST", "Failed: Wrong method.") @@ -30,7 +30,7 @@ class UserCardServiceTest: XCTestCase { } func testConfirmTransactionWithOTPShouldReturnTheRequest() { - let request = UserCardService.confirmTransaction("bar", otp: "otp", transactionId: "foo", transactionCommitRequest: "foobar") + let request = UserCardService.confirmTransaction(cardId: "bar", otp: "otp", transactionId: "foo", transactionCommitRequest: "foobar") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar/transactions/foo/commit", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "POST", "Failed: Wrong method.") @@ -39,7 +39,7 @@ class UserCardServiceTest: XCTestCase { } func testCreateTransactionShouldReturnTheRequest() { - let request = UserCardService.createTransaction("bar", commit: false, transactionRequest: "foobar") + let request = UserCardService.createTransaction(cardId: "bar", commit: false, transactionRequest: "foobar") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar/transactions", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.query.count, 1, "Failed: Wrong number of query parameters.") @@ -49,7 +49,7 @@ class UserCardServiceTest: XCTestCase { } func testCreateTransactionWithCommitShouldReturnTheRequest() { - let request = UserCardService.createTransaction("bar", commit: true, transactionRequest: "foobar") + let request = UserCardService.createTransaction(cardId: "bar", commit: true, transactionRequest: "foobar") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar/transactions", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.query.count, 1, "Failed: Wrong number of query parameters.") @@ -59,7 +59,7 @@ class UserCardServiceTest: XCTestCase { } func testCreateUserCardShouldReturnTheRequest() { - let request = UserCardService.createUserCard("foo") + let request = UserCardService.createUserCard(cardRequest: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "POST", "Failed: Wrong method.") @@ -67,7 +67,7 @@ class UserCardServiceTest: XCTestCase { } func testGetUserCardByIdShouldReturnTheRequest() { - let request = UserCardService.getUserCardById("foo") + let request = UserCardService.getUserCardById(cardId: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/foo", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") @@ -81,7 +81,7 @@ class UserCardServiceTest: XCTestCase { } func testGetUserCardTransactionsShouldReturnTheRequest() { - let request = UserCardService.getUserCardTransactions("bar", range: "foo") + let request = UserCardService.getUserCardTransactions(cardId: "bar", range: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar/transactions", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") @@ -90,7 +90,7 @@ class UserCardServiceTest: XCTestCase { } func testUpdateCardShouldReturnTheRequest() { - let request = UserCardService.updateCard("bar", updateFields: "foo") + let request = UserCardService.updateCard(cardId: "bar", updateFields: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/cards/bar", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "PATCH", "Failed: Wrong method.") diff --git a/Tests/Integration/Service/UserServiceTest.swift b/Tests/IntegrationTests/ServiceTests/UserServiceTest.swift similarity index 91% rename from Tests/Integration/Service/UserServiceTest.swift rename to Tests/IntegrationTests/ServiceTests/UserServiceTest.swift index a5b70f3..23a4cd2 100644 --- a/Tests/Integration/Service/UserServiceTest.swift +++ b/Tests/IntegrationTests/ServiceTests/UserServiceTest.swift @@ -6,7 +6,7 @@ import XCTest class UserServiceTest: XCTestCase { func testCreateContactShouldReturnTheRequest() { - let request = UserService.createContact("foo") + let request = UserService.createContact(contactRequest: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/contacts", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "POST", "Failed: Wrong method.") @@ -14,7 +14,7 @@ class UserServiceTest: XCTestCase { } func testCreateDocumentShouldReturnTheRequest() { - let request = UserService.createDocument("foo") + let request = UserService.createDocument(document: "foo" as AnyObject) XCTAssertEqual(request.url, String(format: "%@/v0/me/documents", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "POST", "Failed: Wrong method.") @@ -57,7 +57,7 @@ class UserServiceTest: XCTestCase { } func testGetUserTransactionsShouldReturnTheRequest() { - let request = UserService.getUserTransactions("foo") + let request = UserService.getUserTransactions(range: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me/transactions", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "GET", "Failed: Wrong method.") @@ -66,7 +66,7 @@ class UserServiceTest: XCTestCase { } func testUpdateUserShouldReturnTheRequest() { - let request = UserService.updateUser("foo") + let request = UserService.updateUser(updatefields: "foo") XCTAssertEqual(request.url, String(format: "%@/v0/me", GlobalConfigurations.UPHOLD_API_URL), "Failed: Wrong URL.") XCTAssertEqual(request.method, "PATCH", "Failed: Wrong method.") diff --git a/Tests/IntegrationTests/UtilTests/HeaderTest.swift b/Tests/IntegrationTests/UtilTests/HeaderTest.swift new file mode 100644 index 0000000..017454e --- /dev/null +++ b/Tests/IntegrationTests/UtilTests/HeaderTest.swift @@ -0,0 +1,36 @@ +import XCTest +import SwiftClient +import UpholdSdk + +/// Header integration tests. +class HeaderTest: XCTestCase { + + func testBuildAuthorizationHeaderShouldReturnAuthorizationHeader() { + XCTAssertEqual(Header.buildAuthorizationHeader(token: "foo")["authorization"], "Bearer foo", "Failed: Wrong value.") + } + + func testBuildRangeHeaderShouldReturnRange() { + XCTAssertEqual(Header.buildRangeHeader(start: 0, end: 5), "items=0-5", "Failed: Wrong value.") + } + + func testGetDefaultHeadersShouldReturnHeaders() { + let headers: [String: String] = Header.getDefaultHeaders() + + XCTAssertEqual(headers["user-agent"], String(format: "uphold-ios-sdk/%@ (%@)", GlobalConfigurations.UPHOLD_SDK_VERSION, GlobalConfigurations.SDK_GITHUB_URL), "Failed: Wrong header.") + } + + func testGetRateLimitValueShouldReturnRateLimit() { + XCTAssertEqual(Header.getRateLimitValue(headers: ["rate-limit-total": "300"]), "300", "Failed: Wrong value.") + XCTAssertNotEqual(Header.getRateLimitValue(headers: ["foobar": "300"]), "300", "Failed: Wrong value.") + } + + func testGetSecondsUntilRateLimitResetShouldReturnResetTime() { + XCTAssertEqual(Header.getSecondsUntilRateLimitReset(headers: ["retry-after": "10"]), "10", "Failed: Wrong value.") + XCTAssertNotEqual(Header.getSecondsUntilRateLimitReset(headers: ["foobar": "10"]), "10", "Failed: Wrong value.") + } + + func testGetTotalNumberOfResults() { + XCTAssertEqual(Header.getTotalNumberOfResults(headers: ["content-range": "0-2/60"]), 60, "Failed: Wrong value.") + } + +} diff --git a/Tests/Integration/Util/ResourcesUtilTest.swift b/Tests/IntegrationTests/UtilTests/ResourcesUtilTest.swift similarity index 61% rename from Tests/Integration/Util/ResourcesUtilTest.swift rename to Tests/IntegrationTests/UtilTests/ResourcesUtilTest.swift index 61563dc..d63e5d4 100644 --- a/Tests/Integration/Util/ResourcesUtilTest.swift +++ b/Tests/IntegrationTests/UtilTests/ResourcesUtilTest.swift @@ -8,11 +8,11 @@ class ResourcesUtilTest: XCTestCase { // swiftlint:disable force_try func testGetValueFromKeyShouldReturnTheValue() { - XCTAssertNotNil(try! ResourcesUtil.getValueFromKey("ConfigurationsPlist", key: "API_URL"), "Failed: Getting resource value failed.") - XCTAssertNotNil(try! ResourcesUtil.getValueFromKey("InfoPlist", key: "CFBundleShortVersionString"), "Failed: Getting resource value failed.") + XCTAssertNotNil(try! ResourcesUtil.getValueFromKey(file: "ConfigurationsPlist", key: "API_URL"), "Failed: Getting resource value failed.") + XCTAssertNotNil(try! ResourcesUtil.getValueFromKey(file: "InfoPlist", key: "CFBundleShortVersionString"), "Failed: Getting resource value failed.") do { - let _ = try ResourcesUtil.getValueFromKey("", key: "foobar") + let _ = try ResourcesUtil.getValueFromKey(file: "", key: "foobar") XCTFail("Error should be ConfigurationMissingError.") } catch let error as ConfigurationMissingError { diff --git a/Tests/Integration/Util/URLUtilsTest.swift b/Tests/IntegrationTests/UtilTests/URLUtilsTest.swift similarity index 79% rename from Tests/Integration/Util/URLUtilsTest.swift rename to Tests/IntegrationTests/UtilTests/URLUtilsTest.swift index a02db9b..e971977 100644 --- a/Tests/Integration/Util/URLUtilsTest.swift +++ b/Tests/IntegrationTests/UtilTests/URLUtilsTest.swift @@ -11,7 +11,7 @@ class URLUtilsTest: XCTestCase { let url = "https://foobar.com/foobiz=foo biz" XCTAssertNil(NSURL(string: url), "Failed: Wrong URL.") - XCTAssertNotNil(try! URLUtils.escapeURL(url), "Failed: Escaping URL failed.") + XCTAssertNotNil(try! URLUtils.escapeURL(url: url), "Failed: Escaping URL failed.") } } diff --git a/Tests/Unit/GlobalConfigurationProductionTest.swift b/Tests/UnitTests/GlobalConfigurationProductionTest.swift similarity index 100% rename from Tests/Unit/GlobalConfigurationProductionTest.swift rename to Tests/UnitTests/GlobalConfigurationProductionTest.swift diff --git a/Tests/Unit/GlobalConfigurationSandboxTest.swift b/Tests/UnitTests/GlobalConfigurationSandboxTest.swift similarity index 100% rename from Tests/Unit/GlobalConfigurationSandboxTest.swift rename to Tests/UnitTests/GlobalConfigurationSandboxTest.swift diff --git a/Tests/Util/Fixtures.swift b/Tests/UtilTests/Fixtures.swift similarity index 94% rename from Tests/Util/Fixtures.swift rename to Tests/UtilTests/Fixtures.swift index 474b493..fe1c18f 100644 --- a/Tests/Util/Fixtures.swift +++ b/Tests/UtilTests/Fixtures.swift @@ -11,7 +11,7 @@ public class Fixtures { - returns: An account. */ public static func loadAccount() -> Account { - return loadAccount(nil) + return loadAccount(fields: nil) } /** @@ -45,7 +45,7 @@ public class Fixtures { - returns: A card. */ public static func loadCard() -> Card { - return loadCard(nil) + return loadCard(fields: nil) } /** @@ -80,14 +80,14 @@ public class Fixtures { var address = [String: String]() - for (index, key) in fakerFields["addressKeys"]!.componentsSeparatedByString(",").enumerate() { - address.updateValue(fakerFields["addressValues"]!.componentsSeparatedByString(",")[index], forKey: key) + for (index, key) in fakerFields["addressKeys"]!.components(separatedBy: ",").enumerated() { + address.updateValue(fakerFields["addressValues"]!.components(separatedBy: ",")[index], forKey: key) } var normalized: [NormalizedCard] = [] - for (index, available) in fakerFields["normalizedAvailable"]!.componentsSeparatedByString(",").enumerate() { - normalized.append(NormalizedCard(available: available, balance: fakerFields["normalizedBalance"]!.componentsSeparatedByString(",")[index], currency: fakerFields["normalizedCurrencies"]!.componentsSeparatedByString(",")[index])) + for (index, available) in fakerFields["normalizedAvailable"]!.components(separatedBy: ",").enumerated() { + normalized.append(NormalizedCard(available: available, balance: fakerFields["normalizedBalance"]!.components(separatedBy: ",")[index], currency: fakerFields["normalizedCurrencies"]!.components(separatedBy: ",")[index])) } let cardSettings = CardSettings(position: NSString(string: fakerFields["settingsPosition"]!).integerValue, starred: NSString(string: fakerFields["settingsStarred"]!).boolValue) @@ -101,7 +101,7 @@ public class Fixtures { - returns: A transaction. */ public static func loadTransaction() -> Transaction { - return loadTransaction(nil) + return loadTransaction(fields: nil) } /** @@ -181,7 +181,7 @@ public class Fixtures { "transactionRefundedById": faker.lorem.characters(amount: 24), "transactionRefunds": faker.lorem.characters(amount: 24), "transactionStatus": faker.lorem.characters(amount: 24), - "transactionType": faker.lorem.characters(amount: 24), + "transactionType": faker.lorem.characters(amount: 24) ] if let fields = fields { @@ -194,8 +194,8 @@ public class Fixtures { let fees = [Fee(amount: fakerFields["feeAmount"]!, currency: fakerFields["feeCurrency"]!, percentage: fakerFields["feePercentage"]!, target: fakerFields["feeTarget"]!, type: fakerFields["feeType"]!)] var sources: [Source] = [] - for (index, ids) in fakerFields["originSourcesId"]!.componentsSeparatedByString(",").enumerate() { - sources.append(Source(id: ids, amount: fakerFields["originSourcesAmount"]!.componentsSeparatedByString(",")[index])) + for (index, ids) in fakerFields["originSourcesId"]!.components(separatedBy: ",").enumerated() { + sources.append(Source(id: ids, amount: fakerFields["originSourcesAmount"]!.components(separatedBy: ",")[index])) } let originMerchant = Merchant(city: fakerFields["originMerchantCity"]!, country: fakerFields["originMerchantCountry"]!, name: fakerFields["originMerchantName"]!, state: fakerFields["originMerchantState"]!, zipCode: fakerFields["originMerchantZipCode"]!) @@ -212,7 +212,7 @@ public class Fixtures { - returns: A user. */ public static func loadUser() -> User { - return loadUser(nil) + return loadUser(fields: nil) } /** @@ -236,7 +236,7 @@ public class Fixtures { "internationalizationUserSettingLanguage": faker.lorem.characters(amount: 5), "internationalizationUserSettingNumberFormat": faker.lorem.characters(amount: 5), "lastName": faker.name.lastName(), - "memberAt": "\(faker.business.creditCardExpiryDate())", + "memberAt": "\(String(describing: faker.business.creditCardExpiryDate()))", "name": faker.name.name(), "settingsOTPLogin": "true", "settingsOTPTransactionsSend": "true", @@ -259,7 +259,7 @@ public class Fixtures { let otp = Otp(login: Login(enabled: NSString(string: fakerFields["settingsOTPLogin"]!).boolValue), transactions: Transactions(send: Send(enabled: NSString(string: fakerFields["settingsOTPTransactionsSend"]!).boolValue), transfer: Transfer(enabled: NSString(string: fakerFields["settingsOTPTransactionsTransfer"]!).boolValue), withdraw: Withdraw(crypto: Crypto(enabled: NSString(string: fakerFields["settingsOTPTransactionsWithdrawCrypto"]!).boolValue)))) let userSettings = UserSettings(currency: fakerFields["currency"]!, hasNewsSubscription: NSString(string: fakerFields["hasNewsSubscription"]!).boolValue, intl: internationalizationUserSettings, otp: otp, theme: fakerFields["theme"]!) - return User(country: fakerFields["country"]!, currencies: fakerFields["currencies"]!.componentsSeparatedByString(","), email: fakerFields["email"]!, firstName: fakerFields["firstName"]!, lastName: fakerFields["lastName"]!, memberAt: fakerFields["memberAt"]!, name: fakerFields["name"]!, settings: userSettings, state: fakerFields["state"]!, status: fakerFields["status"]!, username: fakerFields["username"]!) + return User(country: fakerFields["country"]!, currencies: fakerFields["currencies"]!.components(separatedBy: ","), email: fakerFields["email"]!, firstName: fakerFields["firstName"]!, lastName: fakerFields["lastName"]!, memberAt: fakerFields["memberAt"]!, name: fakerFields["name"]!, settings: userSettings, state: fakerFields["state"]!, status: fakerFields["status"]!, username: fakerFields["username"]!) } } diff --git a/Tests/Util/JSONTestUtils.swift b/Tests/UtilTests/JSONTestUtils.swift similarity index 78% rename from Tests/Util/JSONTestUtils.swift rename to Tests/UtilTests/JSONTestUtils.swift index d59413d..463923b 100644 --- a/Tests/Util/JSONTestUtils.swift +++ b/Tests/UtilTests/JSONTestUtils.swift @@ -11,9 +11,9 @@ public class JSONTestUtils { - returns: The dictionary. */ public static func JSONtoDictionary(json: String) -> [String: AnyObject]? { - if let data = json.dataUsingEncoding(NSUTF8StringEncoding) { + if let data = json.data(using: String.Encoding.utf8) { do { - let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) + let json = try JSONSerialization.jsonObject(with: data, options: []) guard let dictionary = json as? [String: AnyObject] else { return nil diff --git a/Tests/UtilTests/MockBaseModel.swift b/Tests/UtilTests/MockBaseModel.swift new file mode 100644 index 0000000..6afcd9a --- /dev/null +++ b/Tests/UtilTests/MockBaseModel.swift @@ -0,0 +1,17 @@ +import Foundation +import UpholdSdk + +/// Mock base model. +open class MockBaseModel { + + /// The mock uphold REST adapter. + public internal(set) final var mockAdapter: MockRestAdapter + + /** + Constructor. + */ + init() { + self.mockAdapter = MockRestAdapter() + } + +} diff --git a/Tests/UtilTests/MockKeychain.swift b/Tests/UtilTests/MockKeychain.swift new file mode 100644 index 0000000..adf7564 --- /dev/null +++ b/Tests/UtilTests/MockKeychain.swift @@ -0,0 +1,32 @@ +import Foundation +import UpholdSdk + +/// Mock keychain. +open class MockKeychain { + + /** + Deletes the token for a given key from the mock keychain. + */ + func delete(key: String) { + UserDefaults.standard.removeObject(forKey: key) + } + + /** + Gets the token for a given key from the mock keychain. + + - returns: The bearer token. + */ + func get(key: String) -> String? { + let token = UserDefaults.standard.value(forKey: key) as? String + + return token + } + + /** + Sets the token with a given key in the mock keychain. + */ + func set(token: String, key: String) { + UserDefaults.standard.set(token, forKey: key) + } + +} diff --git a/Tests/Util/MockRequest.swift b/Tests/UtilTests/MockRequest.swift similarity index 50% rename from Tests/Util/MockRequest.swift rename to Tests/UtilTests/MockRequest.swift index ba23a56..72443c8 100644 --- a/Tests/Util/MockRequest.swift +++ b/Tests/UtilTests/MockRequest.swift @@ -21,10 +21,10 @@ public class MockRequest: Request { - parameter headers: The request headers. - parameter method: The HTTP method. */ - init(body: String?, code: Int, errorHandler: (NSError) -> Void, headers: [String: String]?, method: String) { + init(body: String?, code: Int, errorHandler: @escaping (Error) -> Void, headers: [String: String]?, method: String) { self.code = code - super.init(method, mockURL, errorHandler) + super.init(method: method, url: mockURL, errorHandler: errorHandler) if let body = body { super.data = body @@ -43,13 +43,13 @@ public class MockRequest: Request { - returns: The mock response. */ func builder(request: NSURLRequest) -> Mockingjay.Response { - let response = NSHTTPURLResponse(URL: request.URL!, statusCode: self.code, HTTPVersion: nil, headerFields: self.headers)! + let response = HTTPURLResponse(url: request.url!, statusCode: self.code, httpVersion: nil, headerFields: self.headers)! - guard let body = self.data else { - return .Success(response, nil) + guard let body = self.data, let data = body as? String, let content = data.data(using: .utf8) else { + return .success(response, nil) } - return .Success(response, body.dataUsingEncoding(NSUTF8StringEncoding)) + return .success(response, .content(content)) } /** @@ -58,14 +58,17 @@ public class MockRequest: Request { - parameter done: The completion handler. - parameter errorHandler: The error handler. */ - public override func end(done: (SwiftClient.Response) -> Void, onError errorHandler: ((NSError) -> Void)? = nil) { - let request = NSMutableURLRequest(URL: NSURL(string: self.mockURL)!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: NSTimeInterval(self.timeout)) - request.HTTPMethod = self.method + public override func end(done: @escaping (SwiftClient.Response) -> Void, onError errorHandler: ((Error) -> Void)? = nil) { + let request = NSMutableURLRequest(url: URL(string: self.mockURL)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: TimeInterval(self.timeout)) + request.httpMethod = self.method self.headers["content-type"] = "json" - switch builder(request) { - case let .Success(response, data): - return done(self.transformer(SwiftClient.Response((response as? NSHTTPURLResponse)!, self, data))) + switch builder(request: request) { + case let .success(response, .content(data)): + return done(self.transformer(SwiftClient.Response(response: (response as? HTTPURLResponse)!, request: self, rawData: data))) + + case let .success(response, .noContent): + return done(self.transformer(SwiftClient.Response(response: (response as? HTTPURLResponse)!, request: self, rawData: nil))) default: return diff --git a/Tests/Util/MockRestAdapter.swift b/Tests/UtilTests/MockRestAdapter.swift similarity index 77% rename from Tests/Util/MockRestAdapter.swift rename to Tests/UtilTests/MockRestAdapter.swift index ef0ffad..2ef5739 100644 --- a/Tests/Util/MockRestAdapter.swift +++ b/Tests/UtilTests/MockRestAdapter.swift @@ -51,7 +51,13 @@ public class MockRestAdapter: UpholdRestAdapter { self.headers = request.headers } - return MockRequest(body: self.body, code: 200, errorHandler: {(error: NSError) -> Void in}, headers: self.headers!, method: request.method) + if let bearerToken = MockSessionManager.sharedInstance.getBearerToken() { + if let mockAuthorizationHeader = Header.buildAuthorizationHeader(token: bearerToken)["authorization"] { + _ = self.headers?.updateValue(mockAuthorizationHeader, forKey: "authorization") + } + } + + return MockRequest(body: self.body, code: 200, errorHandler: {(_: Error) -> Void in}, headers: self.headers!, method: request.method) } /** @@ -62,7 +68,7 @@ public class MockRestAdapter: UpholdRestAdapter { - returns: The mock response. */ public override func buildResponse(request: Request) -> Promise { - return super.buildResponse(request) + return super.buildResponse(request: request) } /** @@ -73,7 +79,7 @@ public class MockRestAdapter: UpholdRestAdapter { - returns: The mock response. */ public override func buildResponse(request: Request) -> Promise<[T]> { - return super.buildResponse(request) + return super.buildResponse(request: request) } } diff --git a/Tests/UtilTests/MockSessionManager.swift b/Tests/UtilTests/MockSessionManager.swift new file mode 100644 index 0000000..445e6bc --- /dev/null +++ b/Tests/UtilTests/MockSessionManager.swift @@ -0,0 +1,64 @@ +import Foundation +import KeychainSwift +import UpholdSdk + +/// Mock session manager. +open class MockSessionManager { + + /// The singleton's shared instance. + static let sharedInstance = MockSessionManager() + + /// The mocked keychain key to access the bearer token. + private static let MOCK_KEYCHAIN_TOKEN_KEY: String = "com.uphold.sdk.mock.token" + + /// The mocked keychain access object. + let keychain: MockKeychain + + /// Queue to manage concurrency. + let lockQueue: DispatchQueue + + /** + Constructor. + */ + init() { + self.keychain = MockKeychain() + self.lockQueue = DispatchQueue(label: GlobalConfigurations.BUNDLE_NAME, attributes: []) + + self.invalidateSession() + } + + /** + Gets the bearer token. + + - returns: The bearer token. + */ + func getBearerToken() -> String? { + guard let token = self.keychain.get(key: MockSessionManager.MOCK_KEYCHAIN_TOKEN_KEY) else { + return nil + } + + return token + } + + /** + Sets the bearer token. + + - parameter token: The bearer token. + */ + func setBearerToken(token: String) { + self.invalidateSession() + + _ = self.lockQueue.sync { + self.keychain.set(token: token, key: MockSessionManager.MOCK_KEYCHAIN_TOKEN_KEY) + } + } + + /** + Deletes the bearer token from the keychain. + */ + func invalidateSession() { + _ = self.lockQueue.sync { + self.keychain.delete(key: MockSessionManager.MOCK_KEYCHAIN_TOKEN_KEY) + } + } +} diff --git a/Tests/UtilTests/MockToken.swift b/Tests/UtilTests/MockToken.swift new file mode 100644 index 0000000..de70eb0 --- /dev/null +++ b/Tests/UtilTests/MockToken.swift @@ -0,0 +1,42 @@ +import Foundation +import PromiseKit +@testable import UpholdSdk + +/// Mock token model. +open class MockToken: MockBaseModel { + + /// The bearer token. + private(set) final var bearerToken: String? + + /** + Constructor. + */ + public override init() { + super.init() + } + + /** + Constructor. + + - parameter bearerToken: The bearer token. + */ + public init(bearerToken: String) { + super.init() + + self.bearerToken = bearerToken + } + + /** + Gets the current user. + + - returns: A promise with the user. + */ + open func getUser() -> Promise { + guard let _ = MockSessionManager.sharedInstance.getBearerToken() else { + return Promise(error: AuthenticationRequiredError(message: "Missing bearer authorization")) + } + + return mockAdapter.buildResponse(request: mockAdapter.buildRequest(request: UserService.getUser())) + } + +} diff --git a/Tests/UtilTests/MockUpholdClient.swift b/Tests/UtilTests/MockUpholdClient.swift new file mode 100644 index 0000000..b083e5e --- /dev/null +++ b/Tests/UtilTests/MockUpholdClient.swift @@ -0,0 +1,54 @@ +import Foundation +import UIKit +import PromiseKit +@testable import UpholdSdk + +/// Mock uphold client. +open class MockUpholdClient: UpholdClient { + + /// The mock uphold user's token. + open private(set) var mockToken: MockToken + + /** + Constructor. + */ + public override init() { + self.mockToken = MockToken() + + super.init() + + _ = self.baseUrl(url: GlobalConfigurations.UPHOLD_API_URL) + } + + /** + Contructor. + + - parameter bearerToken: Authenticated user token. + */ + public convenience init(bearerToken: String) { + self.init() + + self.mockToken = MockToken(bearerToken: bearerToken) + + if let mockToken = self.mockToken.bearerToken { + MockSessionManager.sharedInstance.setBearerToken(token: mockToken) + } + } + + /** + Gets the current user. + + - returns: A promise with the user. + */ + override open func getUser() -> Promise { + return self.mockToken.getUser() + } + + /** + Invalidates the mock client session. + */ + override open func invalidateSession() { + MockSessionManager.sharedInstance.invalidateSession() + } + +} diff --git a/Tests/Util/UpholdTestCase.swift b/Tests/UtilTests/UpholdTestCase.swift similarity index 74% rename from Tests/Util/UpholdTestCase.swift rename to Tests/UtilTests/UpholdTestCase.swift index adf0c62..3ad80ca 100644 --- a/Tests/Util/UpholdTestCase.swift +++ b/Tests/UtilTests/UpholdTestCase.swift @@ -4,9 +4,9 @@ import XCTest class UpholdTestCase: XCTestCase { func wait() { - waitForExpectationsWithTimeout (5, handler: { error in + waitForExpectations(timeout: 5, handler: { error in if let error = error { - print(String(format:"Test timed out with error: %@.", error)) + print(String(format:"Test timed out with error: %@.", error as CVarArg)) } }) } diff --git a/UpholdSdk.podspec.json b/UpholdSdk.podspec.json index 91fa3af..471e720 100644 --- a/UpholdSdk.podspec.json +++ b/UpholdSdk.podspec.json @@ -14,7 +14,7 @@ "tag": "0.7.0" }, "platforms": { - "ios": "9.0" + "ios": "10.0" }, "requires_arc": true, "subspecs": [ @@ -39,16 +39,16 @@ ], "dependencies": { "KeychainSwift": [ - "3.0.13" + "7.0.1" ], "ObjectMapper": [ - "1.2.0" + "2.2.8" ], "PromiseKit": [ - "3.2.1" + "4.1.8" ], "SwiftClient": [ - "2.0.3" + "3.0.1" ] } } diff --git a/UpholdSdk.xcodeproj/project.pbxproj b/UpholdSdk.xcodeproj/project.pbxproj index 14dec67..c825b8c 100644 --- a/UpholdSdk.xcodeproj/project.pbxproj +++ b/UpholdSdk.xcodeproj/project.pbxproj @@ -127,6 +127,16 @@ BC91E8A61BECDB030074C538 /* ReserveTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC91E8A51BECDB030074C538 /* ReserveTest.swift */; }; BC9510CE1C0B92F800E2EDE1 /* UnexpectedResponseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9510CD1C0B92F800E2EDE1 /* UnexpectedResponseError.swift */; }; BC98A4B61C3BE80B00C60A3D /* GlobalConfigurations.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC98A4B51C3BE80B00C60A3D /* GlobalConfigurations.swift */; }; + BC9BEFB51D944837008EBD68 /* MockSessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFB41D944837008EBD68 /* MockSessionManager.swift */; }; + BC9BEFB61D944837008EBD68 /* MockSessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFB41D944837008EBD68 /* MockSessionManager.swift */; }; + BC9BEFB81D944A5A008EBD68 /* MockKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFB71D944A5A008EBD68 /* MockKeychain.swift */; }; + BC9BEFB91D944A5A008EBD68 /* MockKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFB71D944A5A008EBD68 /* MockKeychain.swift */; }; + BC9BEFBB1D9538E0008EBD68 /* MockUpholdClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFBA1D9538E0008EBD68 /* MockUpholdClient.swift */; }; + BC9BEFBC1D9538E0008EBD68 /* MockUpholdClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFBA1D9538E0008EBD68 /* MockUpholdClient.swift */; }; + BC9BEFBE1D9543F7008EBD68 /* MockToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFBD1D9543F7008EBD68 /* MockToken.swift */; }; + BC9BEFBF1D9543F7008EBD68 /* MockToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFBD1D9543F7008EBD68 /* MockToken.swift */; }; + BC9BEFC11D95449A008EBD68 /* MockBaseModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFC01D95449A008EBD68 /* MockBaseModel.swift */; }; + BC9BEFC21D95449A008EBD68 /* MockBaseModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9BEFC01D95449A008EBD68 /* MockBaseModel.swift */; }; BCA15B331C591B3E00DE7D54 /* GlobalConfigurationProductionTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCA15B321C591B3E00DE7D54 /* GlobalConfigurationProductionTest.swift */; }; BCA32A251C18906C0013A347 /* PaginatorTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCA32A241C18906C0013A347 /* PaginatorTest.swift */; }; BCACC4101C5928C2008E7CE7 /* GlobalConfigurationSandboxTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCA15B341C591ECD00DE7D54 /* GlobalConfigurationSandboxTest.swift */; }; @@ -258,6 +268,7 @@ BC02EB181C10503C00FCA0D9 /* TransactionRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionRequest.swift; sourceTree = ""; }; BC02EB1A1C1051B500FCA0D9 /* TransactionDenominationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionDenominationRequest.swift; sourceTree = ""; }; BC0C90221C4CF40400AD0F99 /* OAuth2ServiceTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OAuth2ServiceTest.swift; sourceTree = ""; }; + BC11E87F1D9E7C03006DE7F4 /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = System/Library/Frameworks/MobileCoreServices.framework; sourceTree = SDKROOT; }; BC12F44E1C10691E00EB2E2B /* TransactionCommitRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionCommitRequest.swift; sourceTree = ""; }; BC13CA7B1C9B274100207DAC /* CardRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CardRequest.swift; sourceTree = ""; }; BC1CFA451BDFCF1D00979038 /* LogicError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LogicError.swift; sourceTree = ""; }; @@ -302,7 +313,7 @@ BC3EE5941C1E3E9D0058478D /* PaginatorProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PaginatorProtocol.swift; sourceTree = ""; }; BC3FC4411C3BF0D700487CDC /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; BC3FC4431C3BF0E600487CDC /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - BC4110451C05E5F90063761C /* Fixtures.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Fixtures.swift; path = Util/Fixtures.swift; sourceTree = ""; }; + BC4110451C05E5F90063761C /* Fixtures.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fixtures.swift; sourceTree = ""; }; BC4110471C05E6350063761C /* Balance.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Balance.swift; sourceTree = ""; }; BC41104A1C05E6400063761C /* Currency.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Currency.swift; sourceTree = ""; }; BC41104B1C05E6400063761C /* UserBalance.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserBalance.swift; sourceTree = ""; }; @@ -311,21 +322,21 @@ BC4110501C05E68E0063761C /* Phone.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Phone.swift; sourceTree = ""; }; BC4110561C05E7270063761C /* Fakery.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Fakery.framework; path = Carthage/Build/iOS/Fakery.framework; sourceTree = ""; }; BC431F421C57F51D000685DD /* AuthorizationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthorizationViewController.swift; sourceTree = ""; }; - BC4424141C56A06500FAC537 /* URLUtilsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = URLUtilsTest.swift; path = Util/URLUtilsTest.swift; sourceTree = ""; }; - BC4473C41BD64E2B003B4196 /* UpholdTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UpholdTestCase.swift; path = Util/UpholdTestCase.swift; sourceTree = ""; }; + BC4424141C56A06500FAC537 /* URLUtilsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLUtilsTest.swift; sourceTree = ""; }; + BC4473C41BD64E2B003B4196 /* UpholdTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpholdTestCase.swift; sourceTree = ""; }; BC4A30561BEA655B001B6249 /* Token.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Token.swift; sourceTree = ""; }; BC4A306F1BEA657C001B6249 /* BaseModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BaseModel.swift; sourceTree = ""; }; BC52369E1C5A3EF30088B62D /* ResourcesUtil.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ResourcesUtil.swift; path = Util/ResourcesUtil.swift; sourceTree = ""; }; BC5236A11C5A41120088B62D /* ConfigurationMissingError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConfigurationMissingError.swift; sourceTree = ""; }; - BC5C0A841BD4F77700CEF466 /* MockRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MockRequest.swift; path = Util/MockRequest.swift; sourceTree = ""; }; - BC622E981BD546CA007E767C /* UpholdRestAdapterTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UpholdRestAdapterTest.swift; path = Client/UpholdRestAdapterTest.swift; sourceTree = ""; }; + BC5C0A841BD4F77700CEF466 /* MockRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockRequest.swift; sourceTree = ""; }; + BC622E981BD546CA007E767C /* UpholdRestAdapterTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpholdRestAdapterTest.swift; sourceTree = ""; }; BC6330771C5783A9003DB6D8 /* Configurations.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Configurations.plist; sourceTree = ""; }; BC6330781C5783BE003DB6D8 /* Configurations.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Configurations.plist; sourceTree = ""; }; - BC7E73FC1BEA7BB6006AAE0E /* UpholdClientTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UpholdClientTest.swift; path = Client/UpholdClientTest.swift; sourceTree = ""; }; - BC7E74111BEA80D6006AAE0E /* MockRestAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MockRestAdapter.swift; path = Util/MockRestAdapter.swift; sourceTree = ""; }; + BC7E73FC1BEA7BB6006AAE0E /* UpholdClientTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpholdClientTest.swift; sourceTree = ""; }; + BC7E74111BEA80D6006AAE0E /* MockRestAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockRestAdapter.swift; sourceTree = ""; }; BC81F7011C0753BA0025A1AF /* NormalizedTransaction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NormalizedTransaction.swift; sourceTree = ""; }; BC8386CE1BF2458B00D67F98 /* SessionManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionManager.swift; sourceTree = ""; }; - BC8387171BF395A300D67F98 /* SessionManagerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SessionManagerTest.swift; path = Client/SessionManagerTest.swift; sourceTree = ""; }; + BC8387171BF395A300D67F98 /* SessionManagerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionManagerTest.swift; sourceTree = ""; }; BC8E25731BCFBB4F00C15899 /* ApiLimitExceedError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ApiLimitExceedError.swift; sourceTree = ""; }; BC91E8851BECD80C0074C538 /* Reserve.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Reserve.swift; sourceTree = ""; }; BC91E89B1BECD8270074C538 /* Deposit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Deposit.swift; path = Reserve/Deposit.swift; sourceTree = ""; }; @@ -336,24 +347,29 @@ BC91E8A51BECDB030074C538 /* ReserveTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReserveTest.swift; sourceTree = ""; }; BC9510CD1C0B92F800E2EDE1 /* UnexpectedResponseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UnexpectedResponseError.swift; sourceTree = ""; }; BC98A4B51C3BE80B00C60A3D /* GlobalConfigurations.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GlobalConfigurations.swift; sourceTree = ""; }; + BC9BEFB41D944837008EBD68 /* MockSessionManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockSessionManager.swift; sourceTree = ""; }; + BC9BEFB71D944A5A008EBD68 /* MockKeychain.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockKeychain.swift; sourceTree = ""; }; + BC9BEFBA1D9538E0008EBD68 /* MockUpholdClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockUpholdClient.swift; sourceTree = ""; }; + BC9BEFBD1D9543F7008EBD68 /* MockToken.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockToken.swift; sourceTree = ""; }; + BC9BEFC01D95449A008EBD68 /* MockBaseModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockBaseModel.swift; sourceTree = ""; }; BCA15B321C591B3E00DE7D54 /* GlobalConfigurationProductionTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GlobalConfigurationProductionTest.swift; sourceTree = ""; }; BCA15B341C591ECD00DE7D54 /* GlobalConfigurationSandboxTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GlobalConfigurationSandboxTest.swift; sourceTree = ""; }; BCA32A241C18906C0013A347 /* PaginatorTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PaginatorTest.swift; sourceTree = ""; }; BCACC42E1C5928C2008E7CE7 /* UpholdSdkSandboxTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = UpholdSdkSandboxTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; BCB089901BD52DC20097C475 /* UpholdRestAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpholdRestAdapter.swift; sourceTree = ""; }; - BCC1EB2E1BE3939800F37B7D /* UpholdClientErrorHandlingTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = UpholdClientErrorHandlingTest.swift; path = ErrorHandling/UpholdClientErrorHandlingTest.swift; sourceTree = ""; }; + BCC1EB2E1BE3939800F37B7D /* UpholdClientErrorHandlingTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpholdClientErrorHandlingTest.swift; sourceTree = ""; }; BCC392FC1CE645FA00091B19 /* AccountsService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AccountsService.swift; sourceTree = ""; }; BCC392FF1CE646D700091B19 /* AccountsServiceTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AccountsServiceTest.swift; sourceTree = ""; }; BCC393021CE64E5700091B19 /* Account.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Account.swift; sourceTree = ""; }; BCC9D7181C56377E00671171 /* UpholdSdk.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = UpholdSdk.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - BCC9E0AF1BD10F4300C5C3C8 /* HeaderTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = HeaderTest.swift; path = Util/HeaderTest.swift; sourceTree = ""; }; + BCC9E0AF1BD10F4300C5C3C8 /* HeaderTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HeaderTest.swift; sourceTree = ""; }; BCCBE5561BC6924A00D61852 /* UpholdClientErrorHandling.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpholdClientErrorHandling.swift; sourceTree = ""; }; BCCBE5611BC692E200D61852 /* AuthenticationError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AuthenticationError.swift; sourceTree = ""; }; BCCBE5621BC692E200D61852 /* BadRequestError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BadRequestError.swift; sourceTree = ""; }; BCCBE5631BC692E200D61852 /* UpholdClientError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpholdClientError.swift; sourceTree = ""; }; BCCBE5641BC692E200D61852 /* NotFoundError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NotFoundError.swift; sourceTree = ""; }; BCCBE5651BC692E200D61852 /* UnhandledError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UnhandledError.swift; sourceTree = ""; }; - BCCD62FF1C60D00E0087330A /* ResourcesUtilTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ResourcesUtilTest.swift; path = Util/ResourcesUtilTest.swift; sourceTree = ""; }; + BCCD62FF1C60D00E0087330A /* ResourcesUtilTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResourcesUtilTest.swift; sourceTree = ""; }; BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Production.xcconfig; sourceTree = ""; }; BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Sandbox.xcconfig; sourceTree = ""; }; BCE7757B1C565D67005CE55A /* URLUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = URLUtils.swift; path = Util/URLUtils.swift; sourceTree = ""; }; @@ -364,7 +380,7 @@ BCEB62441BFE28A600094F3A /* OMGHTTPURLRQ.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OMGHTTPURLRQ.framework; path = Carthage/Build/iOS/OMGHTTPURLRQ.framework; sourceTree = ""; }; BCEB62451BFE28A600094F3A /* PromiseKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = PromiseKit.framework; path = Carthage/Build/iOS/PromiseKit.framework; sourceTree = ""; }; BCEB62461BFE28A600094F3A /* SwiftClient.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftClient.framework; path = Carthage/Build/iOS/SwiftClient.framework; sourceTree = ""; }; - BCF38A621C0DFD1B0075E477 /* JSONTestUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = JSONTestUtils.swift; path = Util/JSONTestUtils.swift; sourceTree = ""; }; + BCF38A621C0DFD1B0075E477 /* JSONTestUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONTestUtils.swift; sourceTree = ""; }; BCF4D37E1C62112D00E4BDDA /* Fee.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fee.swift; sourceTree = ""; }; BCF4D3831C62116900E4BDDA /* Login.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Login.swift; sourceTree = ""; }; BCF4D3851C62116900E4BDDA /* Send.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Send.swift; sourceTree = ""; }; @@ -559,27 +575,27 @@ isa = PBXGroup; children = ( BC3FC4431C3BF0E600487CDC /* Info.plist */, - BC2381791BB4627C0060CC80 /* Integration */, - BCA15B311C591B3E00DE7D54 /* Unit */, - BC5C0A7B1BD4F6F800CEF466 /* Util */, + BC2381791BB4627C0060CC80 /* IntegrationTests */, + BCA15B311C591B3E00DE7D54 /* UnitTests */, + BC5C0A7B1BD4F6F800CEF466 /* UtilTests */, ); path = Tests; sourceTree = ""; }; - BC2381791BB4627C0060CC80 /* Integration */ = { + BC2381791BB4627C0060CC80 /* IntegrationTests */ = { isa = PBXGroup; children = ( - BCF5C69A1BCFE82200B6DFAC /* Client */, - BC995DA71BDFD9B50031FA5E /* ErrorHandling */, - BC38D9FA1BB97E4F0044239A /* Service */, - BC23817A1BB4627C0060CC80 /* Model */, - BCA32A231C18904E0013A347 /* Paginator */, - BCC9E0AE1BD10F0500C5C3C8 /* Util */, - ); - path = Integration; + BCF5C69A1BCFE82200B6DFAC /* ClientTests */, + BC995DA71BDFD9B50031FA5E /* ErrorHandlingTests */, + BC38D9FA1BB97E4F0044239A /* ServiceTests */, + BC23817A1BB4627C0060CC80 /* ModelTests */, + BCA32A231C18904E0013A347 /* PaginatorTests */, + BCC9E0AE1BD10F0500C5C3C8 /* UtilTests */, + ); + path = IntegrationTests; sourceTree = ""; }; - BC23817A1BB4627C0060CC80 /* Model */ = { + BC23817A1BB4627C0060CC80 /* ModelTests */ = { isa = PBXGroup; children = ( BC23817B1BB4627C0060CC80 /* CardTest.swift */, @@ -588,10 +604,10 @@ BC23817D1BB4627C0060CC80 /* TransactionTest.swift */, BC23817E1BB4627C0060CC80 /* UserTest.swift */, ); - path = Model; + path = ModelTests; sourceTree = ""; }; - BC38D9FA1BB97E4F0044239A /* Service */ = { + BC38D9FA1BB97E4F0044239A /* ServiceTests */ = { isa = PBXGroup; children = ( BCC392FF1CE646D700091B19 /* AccountsServiceTest.swift */, @@ -601,7 +617,7 @@ BC38D9FD1BB97E4F0044239A /* UserCardServiceTest.swift */, BC38D9FE1BB97E4F0044239A /* UserServiceTest.swift */, ); - path = Service; + path = ServiceTests; sourceTree = ""; }; BC3EE5921C1E3E9D0058478D /* Paginator */ = { @@ -622,16 +638,21 @@ path = Balance; sourceTree = ""; }; - BC5C0A7B1BD4F6F800CEF466 /* Util */ = { + BC5C0A7B1BD4F6F800CEF466 /* UtilTests */ = { isa = PBXGroup; children = ( BC4110451C05E5F90063761C /* Fixtures.swift */, BCF38A621C0DFD1B0075E477 /* JSONTestUtils.swift */, + BC9BEFC01D95449A008EBD68 /* MockBaseModel.swift */, + BC9BEFB71D944A5A008EBD68 /* MockKeychain.swift */, BC5C0A841BD4F77700CEF466 /* MockRequest.swift */, - BC4473C41BD64E2B003B4196 /* UpholdTestCase.swift */, BC7E74111BEA80D6006AAE0E /* MockRestAdapter.swift */, + BC9BEFB41D944837008EBD68 /* MockSessionManager.swift */, + BC9BEFBD1D9543F7008EBD68 /* MockToken.swift */, + BC9BEFBA1D9538E0008EBD68 /* MockUpholdClient.swift */, + BC4473C41BD64E2B003B4196 /* UpholdTestCase.swift */, ); - name = Util; + path = UtilTests; sourceTree = ""; }; BC8939521C3EC7740012BC52 /* Production */ = { @@ -681,39 +702,39 @@ path = Configurations; sourceTree = ""; }; - BC995DA71BDFD9B50031FA5E /* ErrorHandling */ = { + BC995DA71BDFD9B50031FA5E /* ErrorHandlingTests */ = { isa = PBXGroup; children = ( BCC1EB2E1BE3939800F37B7D /* UpholdClientErrorHandlingTest.swift */, ); - name = ErrorHandling; + path = ErrorHandlingTests; sourceTree = ""; }; - BCA15B311C591B3E00DE7D54 /* Unit */ = { + BCA15B311C591B3E00DE7D54 /* UnitTests */ = { isa = PBXGroup; children = ( BCA15B321C591B3E00DE7D54 /* GlobalConfigurationProductionTest.swift */, BCA15B341C591ECD00DE7D54 /* GlobalConfigurationSandboxTest.swift */, ); - path = Unit; + path = UnitTests; sourceTree = ""; }; - BCA32A231C18904E0013A347 /* Paginator */ = { + BCA32A231C18904E0013A347 /* PaginatorTests */ = { isa = PBXGroup; children = ( BCA32A241C18906C0013A347 /* PaginatorTest.swift */, ); - path = Paginator; + path = PaginatorTests; sourceTree = ""; }; - BCC9E0AE1BD10F0500C5C3C8 /* Util */ = { + BCC9E0AE1BD10F0500C5C3C8 /* UtilTests */ = { isa = PBXGroup; children = ( BCC9E0AF1BD10F4300C5C3C8 /* HeaderTest.swift */, BC4424141C56A06500FAC537 /* URLUtilsTest.swift */, BCCD62FF1C60D00E0087330A /* ResourcesUtilTest.swift */, ); - name = Util; + path = UtilTests; sourceTree = ""; }; BCCBE55F1BC692E200D61852 /* ErrorHandling */ = { @@ -738,6 +759,7 @@ BCEB624E1BFE28B500094F3A /* Frameworks */ = { isa = PBXGroup; children = ( + BC11E87F1D9E7C03006DE7F4 /* MobileCoreServices.framework */, BC4110561C05E7270063761C /* Fakery.framework */, BCEB62421BFE28A600094F3A /* KeychainSwift.framework */, BCEB62431BFE28A600094F3A /* ObjectMapper.framework */, @@ -787,14 +809,14 @@ path = Withdraw; sourceTree = ""; }; - BCF5C69A1BCFE82200B6DFAC /* Client */ = { + BCF5C69A1BCFE82200B6DFAC /* ClientTests */ = { isa = PBXGroup; children = ( BC8387171BF395A300D67F98 /* SessionManagerTest.swift */, BC622E981BD546CA007E767C /* UpholdRestAdapterTest.swift */, BC7E73FC1BEA7BB6006AAE0E /* UpholdClientTest.swift */, ); - name = Client; + path = ClientTests; sourceTree = ""; }; BCF656C31BCFCEAE008E2F97 /* Util */ = { @@ -913,14 +935,23 @@ BC2381231BB462170060CC80 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0700; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = Uphold; TargetAttributes = { BC23812B1BB462170060CC80 = { CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0800; }; BC2381351BB462180060CC80 = { CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0800; + ProvisioningStyle = Manual; + }; + BCACC4091C5928C2008E7CE7 = { + LastSwiftMigration = 0800; + }; + BCC9D6D31C56377E00671171 = { + LastSwiftMigration = 0800; }; }; }; @@ -1198,7 +1229,11 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + BC9BEFBE1D9543F7008EBD68 /* MockToken.swift in Sources */, BCA32A251C18906C0013A347 /* PaginatorTest.swift in Sources */, + BC9BEFB81D944A5A008EBD68 /* MockKeychain.swift in Sources */, + BC9BEFBB1D9538E0008EBD68 /* MockUpholdClient.swift in Sources */, + BC9BEFC11D95449A008EBD68 /* MockBaseModel.swift in Sources */, BC38DA021BB97E4F0044239A /* UserServiceTest.swift in Sources */, BC0C90231C4CF40400AD0F99 /* OAuth2ServiceTest.swift in Sources */, BC38DA011BB97E4F0044239A /* UserCardServiceTest.swift in Sources */, @@ -1220,6 +1255,7 @@ BC7E74121BEA80D6006AAE0E /* MockRestAdapter.swift in Sources */, BCC393001CE646D800091B19 /* AccountsServiceTest.swift in Sources */, BC622E991BD546CA007E767C /* UpholdRestAdapterTest.swift in Sources */, + BC9BEFB51D944837008EBD68 /* MockSessionManager.swift in Sources */, BC4424151C56A06500FAC537 /* URLUtilsTest.swift in Sources */, BC2381811BB4627C0060CC80 /* RateTest.swift in Sources */, BC5C0A851BD4F77700CEF466 /* MockRequest.swift in Sources */, @@ -1230,7 +1266,11 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + BC9BEFBF1D9543F7008EBD68 /* MockToken.swift in Sources */, BC0F492B1C5BDA0B00FAE568 /* OAuth2ServiceTest.swift in Sources */, + BC9BEFB91D944A5A008EBD68 /* MockKeychain.swift in Sources */, + BC9BEFBC1D9538E0008EBD68 /* MockUpholdClient.swift in Sources */, + BC9BEFC21D95449A008EBD68 /* MockBaseModel.swift in Sources */, BC0F492C1C5BDA0B00FAE568 /* URLUtilsTest.swift in Sources */, BC865B651C59411F003D67E5 /* SessionManagerTest.swift in Sources */, BC865B661C59411F003D67E5 /* UpholdRestAdapterTest.swift in Sources */, @@ -1252,6 +1292,7 @@ BC865B751C59411F003D67E5 /* JSONTestUtils.swift in Sources */, BCC393011CE646D800091B19 /* AccountsServiceTest.swift in Sources */, BC865B761C59411F003D67E5 /* MockRequest.swift in Sources */, + BC9BEFB61D944837008EBD68 /* MockSessionManager.swift in Sources */, BC865B771C59411F003D67E5 /* UpholdTestCase.swift in Sources */, BC865B781C59411F003D67E5 /* MockRestAdapter.swift in Sources */, BCACC4101C5928C2008E7CE7 /* GlobalConfigurationSandboxTest.swift in Sources */, @@ -1374,8 +1415,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; @@ -1424,8 +1467,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; @@ -1447,6 +1492,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -1458,6 +1504,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1469,10 +1516,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = ProductionDebug; @@ -1481,6 +1530,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1492,10 +1542,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = ProductionRelease; @@ -1504,6 +1556,9 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + DEVELOPMENT_TEAM = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1512,6 +1567,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; + SWIFT_VERSION = 3.0; }; name = ProductionDebug; }; @@ -1519,6 +1575,9 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + DEVELOPMENT_TEAM = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1527,6 +1586,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; + SWIFT_VERSION = 3.0; }; name = ProductionRelease; }; @@ -1534,6 +1594,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1542,6 +1603,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = ProductionDebug; }; @@ -1549,6 +1611,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1557,6 +1620,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = SandboxDebug; }; @@ -1564,6 +1628,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1572,6 +1637,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = ProductionRelease; }; @@ -1579,6 +1645,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1587,6 +1654,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = SandboxRelease; }; @@ -1594,6 +1662,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1605,10 +1674,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = ProductionDebug; @@ -1617,6 +1688,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1628,10 +1700,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = ProductionRelease; @@ -1649,8 +1723,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; @@ -1690,6 +1766,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1701,10 +1778,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = SandboxDebug; @@ -1713,6 +1792,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1724,10 +1804,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = SandboxDebug; @@ -1736,6 +1818,9 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + DEVELOPMENT_TEAM = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1744,6 +1829,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; + SWIFT_VERSION = 3.0; }; name = SandboxDebug; }; @@ -1760,8 +1846,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "iPhone Developer"; @@ -1783,6 +1871,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -1794,6 +1883,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2B1C3FE19B002E02B3 /* Production.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1805,10 +1895,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = SandboxRelease; @@ -1817,6 +1909,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; @@ -1828,10 +1921,12 @@ INFOPLIST_FILE = "$(PROJECT_DIR)/Source/Info.plist"; INFOPLIST_PREPROCESS = NO; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdk; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = SandboxRelease; @@ -1840,6 +1935,9 @@ isa = XCBuildConfiguration; baseConfigurationReference = BCE6DF2C1C3FE1BC002E02B3 /* Sandbox.xcconfig */; buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + DEVELOPMENT_TEAM = ""; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", @@ -1848,6 +1946,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; + SWIFT_VERSION = 3.0; }; name = SandboxRelease; }; diff --git a/UpholdSdk.xcodeproj/xcshareddata/xcschemes/UpholdSdk.xcscheme b/UpholdSdk.xcodeproj/xcshareddata/xcschemes/UpholdSdk.xcscheme index 1c2d05c..a0285ea 100644 --- a/UpholdSdk.xcodeproj/xcshareddata/xcschemes/UpholdSdk.xcscheme +++ b/UpholdSdk.xcodeproj/xcshareddata/xcschemes/UpholdSdk.xcscheme @@ -1,6 +1,6 @@ Date: Wed, 20 Sep 2017 11:37:25 +0100 Subject: [PATCH 2/2] Update swift lint --- .swiftlint.yml | 1 + Source/Client/UpholdRestAdapter.swift | 8 ++++---- Tests/IntegrationTests/ModelTests/UserTest.swift | 4 ++-- .../UtilTests/ResourcesUtilTest.swift | 2 +- UpholdSdk.xcodeproj/project.pbxproj | 16 ++++++++-------- 5 files changed, 16 insertions(+), 15 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index 656518b..60b7e0c 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -8,6 +8,7 @@ disabled_rules: - line_length - type_body_length - variable_name + - unused_optional_binding included: - SampleApplication diff --git a/Source/Client/UpholdRestAdapter.swift b/Source/Client/UpholdRestAdapter.swift index 0890a85..8b2ae9a 100644 --- a/Source/Client/UpholdRestAdapter.swift +++ b/Source/Client/UpholdRestAdapter.swift @@ -86,9 +86,9 @@ open class UpholdRestAdapter { } fulfill(object) - }) { (error: Error) -> Void in + }, onError: { (error: Error) -> Void in reject(error) - } + }) } } @@ -121,9 +121,9 @@ open class UpholdRestAdapter { } fulfill(object) - }) { (error: Error) -> Void in + }, onError: { (error: Error) -> Void in reject(error) - } + }) } } diff --git a/Tests/IntegrationTests/ModelTests/UserTest.swift b/Tests/IntegrationTests/ModelTests/UserTest.swift index a79cf99..b548ca1 100644 --- a/Tests/IntegrationTests/ModelTests/UserTest.swift +++ b/Tests/IntegrationTests/ModelTests/UserTest.swift @@ -66,7 +66,7 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: Mapper().toJSONString(Document(type: "foo", value: "bar"))!) - _ = user.createDocument(document: Document(type: "foo", value: "bar")).then { (document: Document) -> () in + _ = user.createDocument(document: Document(type: "foo", value: "bar")).then { (document: Document) -> Void in XCTAssertEqual(document.type, "foo", "Failed: Wrong card id.") XCTAssertEqual(document.value, "bar", "Failed: Wrong card id.") @@ -473,7 +473,7 @@ class UserTest: UpholdTestCase { let user: User = Fixtures.loadUser() user.adapter = MockRestAdapter(body: json) - _ = user.getDocuments().then { (documents: [Document]) -> () in + _ = user.getDocuments().then { (documents: [Document]) -> Void in XCTAssertEqual(documents.count, 1, "Failed: Wrong number of documents objects.") XCTAssertEqual(documents[0].type, "foo", "Failed: Wrong document type field.") XCTAssertEqual(documents[0].value, "bar", "Failed: Wrong document value.") diff --git a/Tests/IntegrationTests/UtilTests/ResourcesUtilTest.swift b/Tests/IntegrationTests/UtilTests/ResourcesUtilTest.swift index d63e5d4..7d00cba 100644 --- a/Tests/IntegrationTests/UtilTests/ResourcesUtilTest.swift +++ b/Tests/IntegrationTests/UtilTests/ResourcesUtilTest.swift @@ -12,7 +12,7 @@ class ResourcesUtilTest: XCTestCase { XCTAssertNotNil(try! ResourcesUtil.getValueFromKey(file: "InfoPlist", key: "CFBundleShortVersionString"), "Failed: Getting resource value failed.") do { - let _ = try ResourcesUtil.getValueFromKey(file: "", key: "foobar") + _ = try ResourcesUtil.getValueFromKey(file: "", key: "foobar") XCTFail("Error should be ConfigurationMissingError.") } catch let error as ConfigurationMissingError { diff --git a/UpholdSdk.xcodeproj/project.pbxproj b/UpholdSdk.xcodeproj/project.pbxproj index c825b8c..cc3e4d0 100644 --- a/UpholdSdk.xcodeproj/project.pbxproj +++ b/UpholdSdk.xcodeproj/project.pbxproj @@ -1564,7 +1564,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; SWIFT_VERSION = 3.0; @@ -1583,7 +1583,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; SWIFT_VERSION = 3.0; @@ -1600,7 +1600,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 3.0; @@ -1617,7 +1617,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 3.0; @@ -1634,7 +1634,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 3.0; @@ -1651,7 +1651,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 3.0; @@ -1826,7 +1826,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; SWIFT_VERSION = 3.0; @@ -1943,7 +1943,7 @@ "$(PROJECT_DIR)/Carthage/Build/iOS", ); INFOPLIST_FILE = "$(PROJECT_DIR)/Tests/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(PROJECT_DIR)/Carthage/Build/iOS"; PRODUCT_BUNDLE_IDENTIFIER = com.uphold.sdk; PRODUCT_NAME = UpholdSdkTests; SWIFT_VERSION = 3.0;