diff --git a/Ably.podspec b/Ably.podspec index 0b3bb5196..773c884be 100644 --- a/Ably.podspec +++ b/Ably.podspec @@ -3,7 +3,7 @@ Pod::Spec.new do |s| s.version = "1.0.4" s.summary = "iOS client for Ably" s.description = <<-DESC - iOS client library for ably.io, the realtime messaging service, written in Objective-C and ready for Swift 2.0. + iOS client library for ably.io, the realtime messaging service, written in Objective-C and ready for Swift 3.0. DESC s.homepage = "https://www.ably.io" s.license = { :type => 'Apache 2.0', :file => 'LICENSE' } diff --git a/Ably.xcodeproj/project.pbxproj b/Ably.xcodeproj/project.pbxproj index 9beeff64c..78b3fe201 100644 --- a/Ably.xcodeproj/project.pbxproj +++ b/Ably.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 0698443E4343002C872BB397 /* Pods_AblyTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5B7C89E5AD2143F7958C6E2D /* Pods_AblyTests.framework */; }; 1C05CF201AC1D7EB00687AC9 /* ARTRealtime+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 1C05CF1E1AC1D7EB00687AC9 /* ARTRealtime+Private.h */; settings = {ATTRIBUTES = (Private, ); }; }; 1C118A5D1AE63D89006AD19E /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 1C118A5B1AE63D89006AD19E /* Info.plist */; }; 1C118AB81AE6485C006AD19E /* ably-common in Resources */ = {isa = PBXBuildFile; fileRef = 1C118AB61AE6485C006AD19E /* ably-common */; }; @@ -40,8 +41,6 @@ 1CC3D95F1AB7043F0005BEB0 /* ARTRealtimeResumeTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 1CC3D95E1AB7043F0005BEB0 /* ARTRealtimeResumeTest.m */; }; 1CD8DC9F1B1C7315007EAF36 /* ARTDefault.h in Headers */ = {isa = PBXBuildFile; fileRef = 1CD8DC9D1B1C7315007EAF36 /* ARTDefault.h */; settings = {ATTRIBUTES = (Public, ); }; }; 1CD8DCA01B1C7315007EAF36 /* ARTDefault.m in Sources */ = {isa = PBXBuildFile; fileRef = 1CD8DC9E1B1C7315007EAF36 /* ARTDefault.m */; }; - 264A3F128FD04B02A7E7C560 /* Pods_AblyTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0D420C8D021FC663BD30F161 /* Pods_AblyTests.framework */; }; - 273C2F1B5E5F8A35CA0FA91D /* Pods_Ably.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 50923D60C3F1B8A46275A12D /* Pods_Ably.framework */; }; 850BFB4C1B79323C009D0ADD /* ARTPaginatedResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 850BFB4A1B79323C009D0ADD /* ARTPaginatedResult.h */; settings = {ATTRIBUTES = (Public, ); }; }; 850BFB4D1B79323C009D0ADD /* ARTPaginatedResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 850BFB4B1B79323C009D0ADD /* ARTPaginatedResult.m */; }; 851674EF1B7BA5CD00D35169 /* Stats.swift in Sources */ = {isa = PBXBuildFile; fileRef = 851674EE1B7BA5CD00D35169 /* Stats.swift */; }; @@ -133,8 +132,8 @@ D77F02A81DAF8099001B3FF9 /* ARTFallback+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = D77F02A71DAF8099001B3FF9 /* ARTFallback+Private.h */; settings = {ATTRIBUTES = (Private, ); }; }; D780846E1C68B3E50083009D /* NSObject+TestSuite.m in Sources */ = {isa = PBXBuildFile; fileRef = D780846D1C68B3E50083009D /* NSObject+TestSuite.m */; }; D79FF2751D901CD50067FA6A /* ARTRealtime+TestSuite.m in Sources */ = {isa = PBXBuildFile; fileRef = D79FF2741D901CD50067FA6A /* ARTRealtime+TestSuite.m */; }; - D7B17EE31C07208B00A6958E /* ARTConnectionDetails.h in Headers */ = {isa = PBXBuildFile; fileRef = D7B17EE11C07208B00A6958E /* ARTConnectionDetails.h */; settings = {ATTRIBUTES = (Public, ); }; }; - D7B17EE41C07208B00A6958E /* ARTConnectionDetails.m in Sources */ = {isa = PBXBuildFile; fileRef = D7B17EE21C07208B00A6958E /* ARTConnectionDetails.m */; }; + D7B17EE31.0.308B00A6958E /* ARTConnectionDetails.h in Headers */ = {isa = PBXBuildFile; fileRef = D7B17EE11.0.308B00A6958E /* ARTConnectionDetails.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D7B17EE41.0.308B00A6958E /* ARTConnectionDetails.m in Sources */ = {isa = PBXBuildFile; fileRef = D7B17EE21.0.308B00A6958E /* ARTConnectionDetails.m */; }; D7C1B8771BBEA81A0087B55F /* Auth.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7C1B8761BBEA81A0087B55F /* Auth.swift */; }; D7C1B8791BBF5F810087B55F /* ARTAuth+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = D7C1B8781BBF5F460087B55F /* ARTAuth+Private.h */; settings = {ATTRIBUTES = (Private, ); }; }; D7CEF12D1C8D821D004FB242 /* ARTRealtimeChannels+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = D7CEF12C1C8D821D004FB242 /* ARTRealtimeChannels+Private.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -192,7 +191,8 @@ EBD947B71EBB8F2B0005DD16 /* ARTSentry.m in Sources */ = {isa = PBXBuildFile; fileRef = EBD947B51EBB8F2B0005DD16 /* ARTSentry.m */; }; EBD947B81EBB8F2B0005DD16 /* ARTSentry.m in Sources */ = {isa = PBXBuildFile; fileRef = EBD947B51EBB8F2B0005DD16 /* ARTSentry.m */; }; EBFA366E1D58B05000B09AA7 /* ARTRestPresence+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = EB7617701CB6C18C00D0981E /* ARTRestPresence+Private.h */; settings = {ATTRIBUTES = (Private, ); }; }; - FFD88FAD0B9313B189958949 /* Pods_AblySpec.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0EC059350046A107DCB3CD7B /* Pods_AblySpec.framework */; }; + FA86B8010D0DCD25F4C40F73 /* Pods_Ably.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0465E977613804C1D28D6093 /* Pods_Ably.framework */; }; + FEDB0C915C36485216AF6CF7 /* Pods_AblySpec.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2382AA4DD9E4EB0DCCBD81F8 /* Pods_AblySpec.framework */; }; /* End PBXBuildFile section */ /* Begin PBXBuildRule section */ @@ -239,8 +239,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 0D420C8D021FC663BD30F161 /* Pods_AblyTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AblyTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 0EC059350046A107DCB3CD7B /* Pods_AblySpec.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AblySpec.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0465E977613804C1D28D6093 /* Pods_Ably.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Ably.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 1C05CF1E1AC1D7EB00687AC9 /* ARTRealtime+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARTRealtime+Private.h"; sourceTree = ""; }; 1C118A5B1AE63D89006AD19E /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 1C118AB61AE6485C006AD19E /* ably-common */ = {isa = PBXFileReference; lastKnownFileType = folder; name = "ably-common"; path = "../ably-common"; sourceTree = ""; }; @@ -271,13 +270,14 @@ 1CC3D95E1AB7043F0005BEB0 /* ARTRealtimeResumeTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTRealtimeResumeTest.m; sourceTree = ""; }; 1CD8DC9D1B1C7315007EAF36 /* ARTDefault.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARTDefault.h; sourceTree = ""; }; 1CD8DC9E1B1C7315007EAF36 /* ARTDefault.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTDefault.m; sourceTree = ""; }; - 1D77D582F80EFC5ED670591F /* Pods-AblyTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblyTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests.debug.xcconfig"; sourceTree = ""; }; - 23C1F26EF2D084AF531D2E78 /* Pods-AblyTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblyTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests.release.xcconfig"; sourceTree = ""; }; - 2437B67949297F6EDB2CF8DC /* Pods-Ably.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ably.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Ably/Pods-Ably.debug.xcconfig"; sourceTree = ""; }; + 2382AA4DD9E4EB0DCCBD81F8 /* Pods_AblySpec.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AblySpec.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 318521E8A0F0EF25EFF6924B /* Pods-Ably.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ably.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Ably/Pods-Ably.debug.xcconfig"; sourceTree = ""; }; + 39C434E0A565BD99A26370EB /* Pods-AblyTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblyTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests.debug.xcconfig"; sourceTree = ""; }; 3F3D07905A62187E022923A8 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 50923D60C3F1B8A46275A12D /* Pods_Ably.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Ably.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 53AD33463ABC38952C7CFCFC /* Pods-AblySpec.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblySpec.debug.xcconfig"; path = "Pods/Target Support Files/Pods-AblySpec/Pods-AblySpec.debug.xcconfig"; sourceTree = ""; }; - 556227906E1414EBD21D151F /* Pods-AblySpec.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblySpec.release.xcconfig"; path = "Pods/Target Support Files/Pods-AblySpec/Pods-AblySpec.release.xcconfig"; sourceTree = ""; }; + 4E95BA2279A06F30D7AB76ED /* Pods-AblyTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblyTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests.release.xcconfig"; sourceTree = ""; }; + 52B54714DE3B9AA6E2F50EB1 /* Pods-AblySpec.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblySpec.release.xcconfig"; path = "Pods/Target Support Files/Pods-AblySpec/Pods-AblySpec.release.xcconfig"; sourceTree = ""; }; + 5B7C89E5AD2143F7958C6E2D /* Pods_AblyTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AblyTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6A37386B614A9387AB4ABC29 /* Pods-AblySpec.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AblySpec.debug.xcconfig"; path = "Pods/Target Support Files/Pods-AblySpec/Pods-AblySpec.debug.xcconfig"; sourceTree = ""; }; 850BFB4A1B79323C009D0ADD /* ARTPaginatedResult.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARTPaginatedResult.h; sourceTree = ""; }; 850BFB4B1B79323C009D0ADD /* ARTPaginatedResult.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTPaginatedResult.m; sourceTree = ""; }; 851674EE1B7BA5CD00D35169 /* Stats.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Stats.swift; sourceTree = ""; }; @@ -290,7 +290,6 @@ 856AAC9A1B6E326E00B07119 /* ably-common */ = {isa = PBXFileReference; lastKnownFileType = folder; path = "ably-common"; sourceTree = SOURCE_ROOT; }; 85B2C2181B6FE8DE00EA5254 /* CompatibilityMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CompatibilityMacros.h; sourceTree = ""; }; 85F0A60C1B6D03B700EFF45A /* Ably.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = Ably.modulemap; sourceTree = ""; }; - 8DB15FE05AC2F30038FD9E73 /* Pods-Ably.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ably.release.xcconfig"; path = "Pods/Target Support Files/Pods-Ably/Pods-Ably.release.xcconfig"; sourceTree = ""; }; 960D07911A45F1D800ED8C8C /* ARTCrypto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARTCrypto.h; sourceTree = ""; }; 960D07921A45F1D800ED8C8C /* ARTCrypto.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTCrypto.m; sourceTree = ""; }; 960D07951A46FFC300ED8C8C /* ARTRest+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARTRest+Private.h"; sourceTree = ""; }; @@ -334,6 +333,7 @@ 96E408421A38939E00087F77 /* ARTProtocolMessage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTProtocolMessage.m; sourceTree = ""; }; 96E408451A3895E800087F77 /* ARTWebSocketTransport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARTWebSocketTransport.h; sourceTree = ""; }; 96E408461A3895E800087F77 /* ARTWebSocketTransport.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTWebSocketTransport.m; sourceTree = ""; }; + 9B00FA0A76423DABEE840FF7 /* Pods-Ably.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Ably.release.xcconfig"; path = "Pods/Target Support Files/Pods-Ably/Pods-Ably.release.xcconfig"; sourceTree = ""; }; D70EAAEB1BC3376200CD8B9E /* ARTRestChannel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARTRestChannel.h; sourceTree = ""; }; D70EAAEC1BC3376200CD8B9E /* ARTRestChannel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTRestChannel.m; sourceTree = ""; }; D714A63D1C74D4B2002F2CA0 /* NSObject+TestSuite.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSObject+TestSuite.swift"; sourceTree = ""; }; @@ -380,8 +380,8 @@ D780846D1C68B3E50083009D /* NSObject+TestSuite.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+TestSuite.m"; sourceTree = ""; }; D79FF2731D901CD50067FA6A /* ARTRealtime+TestSuite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARTRealtime+TestSuite.h"; sourceTree = ""; }; D79FF2741D901CD50067FA6A /* ARTRealtime+TestSuite.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "ARTRealtime+TestSuite.m"; sourceTree = ""; }; - D7B17EE11C07208B00A6958E /* ARTConnectionDetails.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARTConnectionDetails.h; sourceTree = ""; }; - D7B17EE21C07208B00A6958E /* ARTConnectionDetails.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTConnectionDetails.m; sourceTree = ""; }; + D7B17EE11.0.308B00A6958E /* ARTConnectionDetails.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ARTConnectionDetails.h; sourceTree = ""; }; + D7B17EE21.0.308B00A6958E /* ARTConnectionDetails.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ARTConnectionDetails.m; sourceTree = ""; }; D7C1B8761BBEA81A0087B55F /* Auth.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Auth.swift; sourceTree = ""; }; D7C1B8781BBF5F460087B55F /* ARTAuth+Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "ARTAuth+Private.h"; sourceTree = ""; }; D7CEF12C1C8D821D004FB242 /* ARTRealtimeChannels+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "ARTRealtimeChannels+Private.h"; sourceTree = ""; }; @@ -444,7 +444,7 @@ buildActionMask = 2147483647; files = ( 856AAC8F1B6E304B00B07119 /* Ably.framework in Frameworks */, - FFD88FAD0B9313B189958949 /* Pods_AblySpec.framework in Frameworks */, + FEDB0C915C36485216AF6CF7 /* Pods_AblySpec.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -452,7 +452,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 273C2F1B5E5F8A35CA0FA91D /* Pods_Ably.framework in Frameworks */, + FA86B8010D0DCD25F4C40F73 /* Pods_Ably.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -461,26 +461,13 @@ buildActionMask = 2147483647; files = ( 96BF613D1A35B2AB004CF2B3 /* Ably.framework in Frameworks */, - 264A3F128FD04B02A7E7C560 /* Pods_AblyTests.framework in Frameworks */, + 0698443E4343002C872BB397 /* Pods_AblyTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 121B7E1D3EA9C3EFDF7FE053 /* Pods */ = { - isa = PBXGroup; - children = ( - 2437B67949297F6EDB2CF8DC /* Pods-Ably.debug.xcconfig */, - 8DB15FE05AC2F30038FD9E73 /* Pods-Ably.release.xcconfig */, - 53AD33463ABC38952C7CFCFC /* Pods-AblySpec.debug.xcconfig */, - 556227906E1414EBD21D151F /* Pods-AblySpec.release.xcconfig */, - 1D77D582F80EFC5ED670591F /* Pods-AblyTests.debug.xcconfig */, - 23C1F26EF2D084AF531D2E78 /* Pods-AblyTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 1C1E52E71AB32E69004A690F /* Rest */ = { isa = PBXGroup; children = ( @@ -552,7 +539,7 @@ 856AAC8B1B6E304B00B07119 /* Spec */, 96BF61321A35B2AB004CF2B3 /* Products */, FAFEC5BB8312EB69E84C28D4 /* Frameworks */, - 121B7E1D3EA9C3EFDF7FE053 /* Pods */, + B712803211373535941FE5AA /* Pods */, ); sourceTree = ""; }; @@ -617,6 +604,19 @@ name = "Supporting Files"; sourceTree = ""; }; + B712803211373535941FE5AA /* Pods */ = { + isa = PBXGroup; + children = ( + 318521E8A0F0EF25EFF6924B /* Pods-Ably.debug.xcconfig */, + 9B00FA0A76423DABEE840FF7 /* Pods-Ably.release.xcconfig */, + 6A37386B614A9387AB4ABC29 /* Pods-AblySpec.debug.xcconfig */, + 52B54714DE3B9AA6E2F50EB1 /* Pods-AblySpec.release.xcconfig */, + 39C434E0A565BD99A26370EB /* Pods-AblyTests.debug.xcconfig */, + 4E95BA2279A06F30D7AB76ED /* Pods-AblyTests.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; D746AE301BBC299D003ECEF8 /* Rest */ = { isa = PBXGroup; children = ( @@ -650,9 +650,9 @@ D7D29B401BE3DD0600374295 /* ARTConnection.h */, EB89D40E1C62303E007FA5B7 /* ARTConnection+Private.h */, D7D29B411BE3DEB300374295 /* ARTConnection.m */, - D7B17EE11C07208B00A6958E /* ARTConnectionDetails.h */, + D7B17EE11.0.308B00A6958E /* ARTConnectionDetails.h */, D7D5A69B1CA40C350071BD6D /* ARTConnectionDetails+Private.h */, - D7B17EE21C07208B00A6958E /* ARTConnectionDetails.m */, + D7B17EE21.0.308B00A6958E /* ARTConnectionDetails.m */, D7F1D3751BF4DE72001A4B5E /* ARTRealtimePresence.h */, EB7617711CB6CBFE00D0981E /* ARTRealtimePresence+Private.h */, D7F1D3761BF4DE72001A4B5E /* ARTRealtimePresence.m */, @@ -792,9 +792,9 @@ isa = PBXGroup; children = ( 3F3D07905A62187E022923A8 /* Pods.framework */, - 50923D60C3F1B8A46275A12D /* Pods_Ably.framework */, - 0EC059350046A107DCB3CD7B /* Pods_AblySpec.framework */, - 0D420C8D021FC663BD30F161 /* Pods_AblyTests.framework */, + 0465E977613804C1D28D6093 /* Pods_Ably.framework */, + 2382AA4DD9E4EB0DCCBD81F8 /* Pods_AblySpec.framework */, + 5B7C89E5AD2143F7958C6E2D /* Pods_AblyTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -869,7 +869,7 @@ D746AE431BBC5CD0003ECEF8 /* ARTRealtimeChannel+Private.h in Headers */, D746AE251BBB611C003ECEF8 /* ARTChannel+Private.h in Headers */, D7F1D3731BF4DE07001A4B5E /* ARTRestPresence.h in Headers */, - D7B17EE31C07208B00A6958E /* ARTConnectionDetails.h in Headers */, + D7B17EE31.0.308B00A6958E /* ARTConnectionDetails.h in Headers */, D7F2B8B21E42410D00B65151 /* ARTPresenceMessage+Private.h in Headers */, EBFA366E1D58B05000B09AA7 /* ARTRestPresence+Private.h in Headers */, EB2D85011CD769C800F23CDA /* ARTOSReachability.h in Headers */, @@ -898,12 +898,12 @@ isa = PBXNativeTarget; buildConfigurationList = 856AAC921B6E304B00B07119 /* Build configuration list for PBXNativeTarget "AblySpec" */; buildPhases = ( - 0CFA28EF19AC12BEB98B67BA /* [CP] Check Pods Manifest.lock */, + F4859C5FC59DE6253E96EE08 /* [CP] Check Pods Manifest.lock */, 856AAC861B6E304B00B07119 /* Sources */, 856AAC871B6E304B00B07119 /* Frameworks */, 856AAC881B6E304B00B07119 /* Resources */, - A08ED191533D7C05CF3B1358 /* [CP] Embed Pods Frameworks */, - A2626968608E7641E6B1B91D /* [CP] Copy Pods Resources */, + 5A2F4A778F20519245535797 /* [CP] Embed Pods Frameworks */, + C7CC8985FA5C6556A8DF2514 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -919,13 +919,12 @@ isa = PBXNativeTarget; buildConfigurationList = 96BF61471A35B2AB004CF2B3 /* Build configuration list for PBXNativeTarget "Ably" */; buildPhases = ( - 960F84BD638CCB7D20786C8C /* [CP] Check Pods Manifest.lock */, + 1D9083EC07551819730E46A9 /* [CP] Check Pods Manifest.lock */, 96BF612C1A35B2AB004CF2B3 /* Sources */, 96BF612D1A35B2AB004CF2B3 /* Frameworks */, 96BF612E1A35B2AB004CF2B3 /* Headers */, 96BF612F1A35B2AB004CF2B3 /* Resources */, - EBD947B21EBB7FD90005DD16 /* ShellScript */, - D521D5640C764B9BE193A9C0 /* [CP] Copy Pods Resources */, + 083D6F601E7A4A36D54A0D68 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -940,13 +939,13 @@ isa = PBXNativeTarget; buildConfigurationList = 96BF614A1A35B2AB004CF2B3 /* Build configuration list for PBXNativeTarget "AblyTests" */; buildPhases = ( - 69292B8293A8743CB0AA4D90 /* [CP] Check Pods Manifest.lock */, + BE0466D5EC1E3C2E5BFA8555 /* [CP] Check Pods Manifest.lock */, 96BF61381A35B2AB004CF2B3 /* Sources */, 96BF61391A35B2AB004CF2B3 /* Frameworks */, 96BF613A1A35B2AB004CF2B3 /* Resources */, 1C5DA0141A6E5F8A00A2B7EF /* Copy Files */, - 3721DD0426946FEE30506043 /* [CP] Embed Pods Frameworks */, - 0CB78F085111D688E00963CF /* [CP] Copy Pods Resources */, + F79A66600C11945BE067DFC1 /* [CP] Embed Pods Frameworks */, + 76E03E134A66AC85FEDECBE9 /* [CP] Copy Pods Resources */, ); buildRules = ( 1C5DA0131A6E5F2700A2B7EF /* PBXBuildRule */, @@ -972,12 +971,14 @@ TargetAttributes = { 856AAC891B6E304B00B07119 = { CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0820; }; 96BF61301A35B2AB004CF2B3 = { CreatedOnToolsVersion = 6.1.1; }; 96BF613B1A35B2AB004CF2B3 = { CreatedOnToolsVersion = 6.1.1; + LastSwiftMigration = 0820; }; }; }; @@ -1029,7 +1030,7 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 0CB78F085111D688E00963CF /* [CP] Copy Pods Resources */ = { + 083D6F601E7A4A36D54A0D68 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -1041,10 +1042,10 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests-resources.sh\"\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Ably/Pods-Ably-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 0CFA28EF19AC12BEB98B67BA /* [CP] Check Pods Manifest.lock */ = { + 1D9083EC07551819730E46A9 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -1056,10 +1057,10 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - 3721DD0426946FEE30506043 /* [CP] Embed Pods Frameworks */ = { + 5A2F4A778F20519245535797 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -1071,25 +1072,25 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests-frameworks.sh\"\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AblySpec/Pods-AblySpec-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 69292B8293A8743CB0AA4D90 /* [CP] Check Pods Manifest.lock */ = { + 76E03E134A66AC85FEDECBE9 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "[CP] Check Pods Manifest.lock"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 960F84BD638CCB7D20786C8C /* [CP] Check Pods Manifest.lock */ = { + BE0466D5EC1E3C2E5BFA8555 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -1101,25 +1102,10 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; - showEnvVarsInLog = 0; - }; - A08ED191533D7C05CF3B1358 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AblySpec/Pods-AblySpec-frameworks.sh\"\n"; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - A2626968608E7641E6B1B91D /* [CP] Copy Pods Resources */ = { + C7CC8985FA5C6556A8DF2514 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -1134,33 +1120,35 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AblySpec/Pods-AblySpec-resources.sh\"\n"; showEnvVarsInLog = 0; }; - D521D5640C764B9BE193A9C0 /* [CP] Copy Pods Resources */ = { + F4859C5FC59DE6253E96EE08 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "[CP] Copy Pods Resources"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Ably/Pods-Ably-resources.sh\"\n"; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - EBD947B21EBB7FD90005DD16 /* ShellScript */ = { + F79A66600C11945BE067DFC1 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/bash; - shellScript = "if which sentry-cli >/dev/null; then\nexport SENTRY_ORG=ably\nexport SENTRY_PROJECT=ably-ios\nexport SENTRY_AUTH_TOKEN=dcf69b8b629b45a1b6baf77d138fbf8efd107b7159dd4bd2b932ba31564cfde5\nexport SENTRY_URL='https://errors.ably.io/'\nERROR=$(sentry-cli upload-dsym 2>&1 >/dev/null)\nif [ ! $? -eq 0 ]; then\necho \"warning: sentry-cli - $ERROR\"\nfi\nelse\necho \"warning: sentry-cli not installed, download from https://github.com/getsentry/sentry-cli/releases\"\nfi\n"; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AblyTests/Pods-AblyTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ @@ -1214,7 +1202,7 @@ 960D07941A45F1D800ED8C8C /* ARTCrypto.m in Sources */, D7D8F8221BC2BE16009718F2 /* ARTAuthOptions.m in Sources */, 1C55427D1B148306003068DB /* ARTStatus.m in Sources */, - D7B17EE41C07208B00A6958E /* ARTConnectionDetails.m in Sources */, + D7B17EE41.0.308B00A6958E /* ARTConnectionDetails.m in Sources */, 96BF61591A35B52C004CF2B3 /* ARTHttp.m in Sources */, D73692001DB788C40062C150 /* ARTAuthDetails.m in Sources */, 1C578E201B3435CA00EF46EC /* ARTFallback.m in Sources */, @@ -1298,7 +1286,7 @@ /* Begin XCBuildConfiguration section */ 856AAC931B6E304B00B07119 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 53AD33463ABC38952C7CFCFC /* Pods-AblySpec.debug.xcconfig */; + baseConfigurationReference = 6A37386B614A9387AB4ABC29 /* Pods-AblySpec.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CLANG_ENABLE_MODULES = YES; @@ -1309,13 +1297,13 @@ PRODUCT_BUNDLE_IDENTIFIER = "io.ably.$(PRODUCT_NAME)"; PRODUCT_NAME = AblySpec; SWIFT_OBJC_BRIDGING_HEADER = "Spec/AblySpec-Bridging-Header.h"; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Debug; }; 856AAC941B6E304B00B07119 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 556227906E1414EBD21D151F /* Pods-AblySpec.release.xcconfig */; + baseConfigurationReference = 52B54714DE3B9AA6E2F50EB1 /* Pods-AblySpec.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CLANG_ENABLE_MODULES = YES; @@ -1327,7 +1315,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "io.ably.$(PRODUCT_NAME)"; PRODUCT_NAME = AblySpec; SWIFT_OBJC_BRIDGING_HEADER = "Spec/AblySpec-Bridging-Header.h"; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -1425,7 +1413,7 @@ }; 96BF61481A35B2AB004CF2B3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2437B67949297F6EDB2CF8DC /* Pods-Ably.debug.xcconfig */; + baseConfigurationReference = 318521E8A0F0EF25EFF6924B /* Pods-Ably.debug.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; @@ -1439,13 +1427,13 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SEPARATE_STRIP = YES; STRIP_STYLE = all; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Debug; }; 96BF61491A35B2AB004CF2B3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8DB15FE05AC2F30038FD9E73 /* Pods-Ably.release.xcconfig */; + baseConfigurationReference = 9B00FA0A76423DABEE840FF7 /* Pods-Ably.release.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEFINES_MODULE = YES; @@ -1459,33 +1447,33 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SEPARATE_STRIP = YES; STRIP_STYLE = all; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Release; }; 96BF614B1A35B2AB004CF2B3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 1D77D582F80EFC5ED670591F /* Pods-AblyTests.debug.xcconfig */; + baseConfigurationReference = 39C434E0A565BD99A26370EB /* Pods-AblyTests.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; GCC_PREPROCESSOR_DEFINITIONS = "$(inherited)"; INFOPLIST_FILE = Tests/Info.plist; PRODUCT_BUNDLE_IDENTIFIER = "io.ably.$(PRODUCT_NAME)"; PRODUCT_NAME = AblyTests; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; VALID_ARCHS = "arm64 armv7 armv7s"; }; name = Debug; }; 96BF614C1A35B2AB004CF2B3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 23C1F26EF2D084AF531D2E78 /* Pods-AblyTests.release.xcconfig */; + baseConfigurationReference = 4E95BA2279A06F30D7AB76ED /* Pods-AblyTests.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; INFOPLIST_FILE = Tests/Info.plist; PRODUCT_BUNDLE_IDENTIFIER = "io.ably.$(PRODUCT_NAME)"; PRODUCT_NAME = AblyTests; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; VALID_ARCHS = "arm64 armv7 armv7s"; }; name = Release; diff --git a/Podfile b/Podfile index 870c3087b..6a7c8ad3c 100644 --- a/Podfile +++ b/Podfile @@ -10,11 +10,11 @@ end def test_pods project_pods - pod 'Quick', '0.9.3' - pod 'Nimble', '4.1.0' + pod 'Quick', '1.1.0' + pod 'Nimble', '7.0.0' # Helpers pod 'Aspects' - pod 'SwiftyJSON', '2.4.0' + pod 'SwiftyJSON', '3.1.4' end target 'Ably' do diff --git a/Podfile.lock b/Podfile.lock index acb142958..57d9707d9 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -64,29 +64,29 @@ PODS: - KSCrashAblyFork/Reporting/Tools (1.15.8-ably-1): - KSCrashAblyFork/Recording - msgpack (0.1.8) - - Nimble (4.1.0) - - Quick (0.9.3) + - Nimble (7.0.0) + - Quick (1.1.0) - SocketRocket (0.5.1) - - SwiftyJSON (2.4.0) + - SwiftyJSON (3.1.4) DEPENDENCIES: - Aspects - KSCrashAblyFork (= 1.15.8-ably-1) - msgpack (= 0.1.8) - - Nimble (= 4.1.0) - - Quick (= 0.9.3) + - Nimble (= 7.0.0) + - Quick (= 1.1.0) - SocketRocket (= 0.5.1) - - SwiftyJSON (= 2.4.0) + - SwiftyJSON (= 3.1.4) SPEC CHECKSUMS: Aspects: 7595ba96a6727a58ebcbfc954497fc5d2fdde546 KSCrashAblyFork: 6d0dd5b033710109a8fdde28103eeb0e7f9ba1f7 msgpack: 97491d2ea799408f4694f2c7d7fd79baf77853dd - Nimble: 97a0a4cae5124c117115634b2d055d8c97d0af19 - Quick: 13a2a2b19a5d8e3ed4fd0c36ee46597fd77ebf71 + Nimble: 874982b605d4d752fcac6be695d13c502de84b1b + Quick: dafc587e21eed9f4cab3249b9f9015b0b7a7f71d SocketRocket: d57c7159b83c3c6655745cd15302aa24b6bae531 - SwiftyJSON: 96918c1bf505efa50c4f72957018dd3452090c9c + SwiftyJSON: c2842d878f95482ffceec5709abc3d05680c0220 -PODFILE CHECKSUM: 160cf53ef13d4ed09e5e81c2f2840457b07e012a +PODFILE CHECKSUM: 51df8c07c1f9b8c5dc1c7d7b7c47457ddfc72d30 -COCOAPODS: 1.2.1 +COCOAPODS: 1.2.0 diff --git a/Source/ARTWebSocketTransport.m b/Source/ARTWebSocketTransport.m index e90b501ac..a2025b1ad 100644 --- a/Source/ARTWebSocketTransport.m +++ b/Source/ARTWebSocketTransport.m @@ -272,7 +272,6 @@ - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reas break; case ARTWsBuggyClose: case ARTWsGoingAway: - case ARTWsAbnormalClose: // Connectivity issue [s.delegate realtimeTransportDisconnected:s withError:nil]; break; diff --git a/Spec/Auth.swift b/Spec/Auth.swift index bd8c8e1f7..c6b651355 100644 --- a/Spec/Auth.swift +++ b/Spec/Auth.swift @@ -47,9 +47,9 @@ class Auth : QuickSpec { } } - let key64 = NSString(string: "\(client.options.key!)") - .dataUsingEncoding(NSUTF8StringEncoding)! - .base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) + let key64 = "\(client.options.key!)" + .data(using: .utf8)! + .base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) let expectedAuthorization = "Basic \(key64)" @@ -67,7 +67,7 @@ class Auth : QuickSpec { it("should be default when an API key is set") { let client = ARTRest(options: ARTClientOptions(key: "fake:key")) - expect(client.auth.method).to(equal(ARTAuthMethod.Basic)) + expect(client.auth.method).to(equal(ARTAuthMethod.basic)) } } @@ -92,7 +92,7 @@ class Auth : QuickSpec { fail("No request found") return } - guard let url = request.URL else { + guard let url = request.url else { fail("Request is invalid") return } @@ -115,7 +115,7 @@ class Auth : QuickSpec { fail("No request found") return } - guard let url = request.URL else { + guard let url = request.url else { fail("Request is invalid") return } @@ -161,7 +161,7 @@ class Auth : QuickSpec { let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() if let transport = client.transport as? TestProxyTransport, let query = transport.lastUrl?.query { @@ -182,7 +182,7 @@ class Auth : QuickSpec { let client = ARTRest(options: options) - expect(client.auth.method).to(equal(ARTAuthMethod.Token)) + expect(client.auth.method).to(equal(ARTAuthMethod.token)) } } @@ -206,7 +206,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(UInt(error.code)).to(equal(ARTState.RequestTokenFailed.rawValue)) + expect(UInt(error.code)).to(equal(ARTState.requestTokenFailed.rawValue)) done() } } @@ -229,7 +229,7 @@ class Auth : QuickSpec { expect(realtime.options.key).to(beNil()) expect(realtime.options.authCallback).to(beNil()) expect(realtime.options.authUrl).to(beNil()) - realtime.setTransportClass(TestProxyTransport.self) + realtime.setTransport(TestProxyTransport.self) let channel = realtime.channels.get("test") @@ -239,8 +239,8 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(UInt(error.code)).to(equal(ARTState.RequestTokenFailed.rawValue)) - expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(UInt(error.code)).to(equal(ARTState.requestTokenFailed.rawValue)) + expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.failed)) done() } } @@ -287,10 +287,10 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Failed) { _ in + realtime.connection.once(.failed) { _ in fail("Should not reach Failed state"); done(); return } - realtime.connection.once(.Disconnected) { stateChange in + realtime.connection.once(.disconnected) { stateChange in guard let errorInfo = stateChange?.reason else { fail("ErrorInfo is nil"); done(); return } @@ -306,8 +306,8 @@ class Auth : QuickSpec { let options = AblyTests.commonAppSetup() options.authCallback = { tokenParams, completion in let token = getTestToken() - let invalidToken = String(token.characters.reverse()) - completion(invalidToken, nil) + let invalidToken = String(token.characters.reversed()) + completion(invalidToken as ARTTokenDetailsCompatible?, nil) } options.autoConnect = false @@ -315,14 +315,14 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Failed) { stateChange in + realtime.connection.once(.failed) { stateChange in guard let errorInfo = stateChange?.reason else { fail("ErrorInfo is nil"); done(); return } expect(errorInfo.message).to(contain("No application found with id")) done() } - realtime.connection.once(.Disconnected) { _ in + realtime.connection.once(.disconnected) { _ in fail("Should not reach Disconnected state"); done(); return } realtime.connect() @@ -337,7 +337,7 @@ class Auth : QuickSpec { // - authCallback and authUrl are both specified let cases: [String: (ARTAuthOptions) -> ()] = [ "useTokenAuth and no key":{ $0.useTokenAuth = true }, - "authCallback and authUrl":{ $0.authCallback = { params, callback in /*nothing*/ }; $0.authUrl = NSURL(string: "http://auth.ably.io") } + "authCallback and authUrl":{ $0.authCallback = { params, callback in /*nothing*/ }; $0.authUrl = NSURL(string: "http://auth.ably.io") as URL? } ] for (caseName, caseSetter) in cases { @@ -358,16 +358,16 @@ class Auth : QuickSpec { it("if the connection is CONNECTING, then the connection attempt should be treated as unsuccessful") { let options = AblyTests.clientOptions() options.autoConnect = false - options.authUrl = NSURL(string: "http://echo.ably.io")! + options.authUrl = NSURL(string: "http://echo.ably.io")! as URL let realtime = ARTRealtime(options: options) defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Disconnected) { stateChange in + realtime.connection.once(.disconnected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) guard let errorInfo = stateChange.reason else { fail("ErrorInfo is nil"); done(); return } @@ -388,27 +388,27 @@ class Auth : QuickSpec { it("if the connection is CONNECTED, then the connection should remain CONNECTED") { let token = getTestToken() let options = AblyTests.clientOptions() - options.authUrl = NSURL(string: "http://echo.ably.io")! - options.authParams = [NSURLQueryItem]() - options.authParams?.append(NSURLQueryItem(name: "type", value: "text")) - options.authParams?.append(NSURLQueryItem(name: "body", value: token)) + options.authUrl = NSURL(string: "http://echo.ably.io")! as URL + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams?.append(NSURLQueryItem(name: "type", value: "text") as URLQueryItem) + options.authParams?.append(NSURLQueryItem(name: "body", value: token) as URLQueryItem) let realtime = ARTRealtime(options: options) defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } } // Token reauth will fail - realtime.options.authParams = [NSURLQueryItem]() + realtime.options.authParams = [NSURLQueryItem]() as [URLQueryItem]? // Inject AUTH let authMessage = ARTProtocolMessage() - authMessage.action = ARTProtocolMessageAction.Auth + authMessage.action = ARTProtocolMessageAction.auth realtime.transport?.receive(authMessage) expect(realtime.connection.errorReason).toEventuallyNot(beNil(), timeout: testTimeout) @@ -418,7 +418,7 @@ class Auth : QuickSpec { expect(errorInfo.code) == 80019 expect(errorInfo.message).to(contain("body param is required")) - expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.connected)) } } @@ -435,11 +435,11 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Disconnected) { stateChange in + realtime.connection.once(.disconnected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) guard let errorInfo = stateChange.reason else { fail("ErrorInfo is nil"); done(); return } @@ -455,7 +455,7 @@ class Auth : QuickSpec { expect(errorInfo.code) == 80019 expect(errorInfo.message).to(contain("hostname could not be found")) - expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.Disconnected), timeout: testTimeout) + expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.disconnected), timeout: testTimeout) } // RSA4c3 @@ -468,7 +468,7 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -481,7 +481,7 @@ class Auth : QuickSpec { // Inject AUTH let authMessage = ARTProtocolMessage() - authMessage.action = ARTProtocolMessageAction.Auth + authMessage.action = ARTProtocolMessageAction.auth realtime.transport?.receive(authMessage) expect(realtime.connection.errorReason).toEventuallyNot(beNil(), timeout: testTimeout) @@ -491,7 +491,7 @@ class Auth : QuickSpec { expect(errorInfo.code) == 80019 expect(errorInfo.message).to(contain("hostname could not be found")) - expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.connected)) } } @@ -501,21 +501,21 @@ class Auth : QuickSpec { it("if the connection is CONNECTING, then the connection attempt should be treated as unsuccessful") { var options = AblyTests.clientOptions() options.autoConnect = false - options.authUrl = NSURL(string: "http://echo.ably.io")! - options.authParams = [NSURLQueryItem]() - options.authParams?.append(NSURLQueryItem(name: "type", value: "json")) + options.authUrl = NSURL(string: "http://echo.ably.io")! as URL + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams?.append(NSURLQueryItem(name: "type", value: "json") as URLQueryItem) let invalidTokenFormat = "{secret_token:xxx}" - options.authParams?.append(NSURLQueryItem(name: "body", value: invalidTokenFormat)) + options.authParams?.append(NSURLQueryItem(name: "body", value: invalidTokenFormat) as URLQueryItem) let realtime = ARTRealtime(options: options) defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Disconnected) { stateChange in + realtime.connection.once(.disconnected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) guard let errorInfo = stateChange.reason else { fail("ErrorInfo is nil"); done(); return } @@ -531,48 +531,48 @@ class Auth : QuickSpec { expect(errorInfo.code) == 80019 expect(errorInfo.message).to(contain("content response cannot be used for token request")) - expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.Disconnected), timeout: testTimeout) + expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.disconnected), timeout: testTimeout) } // RSA4c3 it("if the connection is CONNECTED, then the connection should remain CONNECTED") { var options = AblyTests.clientOptions() - options.authUrl = NSURL(string: "http://echo.ably.io")! - options.authParams = [NSURLQueryItem]() - options.authParams?.append(NSURLQueryItem(name: "type", value: "text")) + options.authUrl = NSURL(string: "http://echo.ably.io")! as URL + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams?.append(NSURLQueryItem(name: "type", value: "text") as URLQueryItem) let token = getTestToken() - options.authParams?.append(NSURLQueryItem(name: "body", value: token)) + options.authParams?.append(NSURLQueryItem(name: "body", value: token) as URLQueryItem) let realtime = ARTRealtime(options: options) defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } } // Token should renew and fail - let invalidToken = String(token.characters.reverse()) - realtime.options.authParams = [NSURLQueryItem]() - realtime.options.authParams?.append(NSURLQueryItem(name: "type", value: "json")) + let invalidToken = String(token.characters.reversed()) + realtime.options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + realtime.options.authParams?.append(NSURLQueryItem(name: "type", value: "json") as URLQueryItem) let invalidTokenFormat = "{secret_token:xxx}" - realtime.options.authParams?.append(NSURLQueryItem(name: "body", value: invalidTokenFormat)) + realtime.options.authParams?.append(NSURLQueryItem(name: "body", value: invalidTokenFormat) as URLQueryItem) realtime.connection.on() { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange should not be nil"); return } - if stateChange.current != .Connected { + if stateChange.current != .connected { fail("Connection should remain connected") } } // Inject AUTH let authMessage = ARTProtocolMessage() - authMessage.action = ARTProtocolMessageAction.Auth + authMessage.action = ARTProtocolMessageAction.auth realtime.transport?.receive(authMessage) expect(realtime.connection.errorReason).toEventuallyNot(beNil(), timeout: testTimeout) @@ -582,7 +582,7 @@ class Auth : QuickSpec { expect(errorInfo.code) == 80019 expect(errorInfo.message).to(contain("content response cannot be used for token request")) - expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.connected)) } } @@ -603,7 +603,7 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Disconnected) { stateChange in + realtime.connection.once(.disconnected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } @@ -622,7 +622,7 @@ class Auth : QuickSpec { expect(errorInfo.code) == 80019 expect(errorInfo.message).to(contain("timed out")) - expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.Disconnected), timeout: testTimeout) + expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.disconnected), timeout: testTimeout) } // RSA4c3 @@ -637,7 +637,7 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -655,7 +655,7 @@ class Auth : QuickSpec { // Inject AUTH let authMessage = ARTProtocolMessage() - authMessage.action = ARTProtocolMessageAction.Auth + authMessage.action = ARTProtocolMessageAction.auth realtime.transport?.receive(authMessage) expect(realtime.connection.errorReason).toEventuallyNot(beNil(), timeout: testTimeout) @@ -665,7 +665,7 @@ class Auth : QuickSpec { expect(errorInfo.code) == 80019 expect(errorInfo.message).to(contain("timed out")) - expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(realtime.connection.state).to(equal(ARTRealtimeConnectionState.connected)) } } } @@ -689,7 +689,7 @@ class Auth : QuickSpec { // Token client.auth.authorize(nil, options: nil) { tokenDetails, error in expect(error).to(beNil()) - expect(client.auth.method).to(equal(ARTAuthMethod.Token)) + expect(client.auth.method).to(equal(ARTAuthMethod.token)) guard let tokenDetails = tokenDetails else { fail("TokenDetails is nil"); done(); return } @@ -699,9 +699,9 @@ class Auth : QuickSpec { } switch extractBodyAsMsgPack(testHTTPExecutor.requests.first) { - case .Failure(let error): + case .failure(let error): XCTFail(error) - case .Success(let httpBody): + case .success(let httpBody): guard let requestedClientId = httpBody.unbox["clientId"] as? String else { XCTFail("No clientId field in HTTPBody"); return } expect(requestedClientId).to(equal(expectedClientId)) } @@ -715,7 +715,7 @@ class Auth : QuickSpec { let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() waitUntil(timeout: testTimeout) { done in @@ -723,7 +723,7 @@ class Auth : QuickSpec { let stateChange = stateChange! let state = stateChange.current let error = stateChange.reason - if state == .Connected && error == nil { + if state == .connected && error == nil { let currentChannel = client.channels.get("test") currentChannel.subscribe({ message in done() @@ -736,7 +736,7 @@ class Auth : QuickSpec { guard let transport = client.transport as? TestProxyTransport else { fail("Transport is nil"); return } - guard let connectedMessage = transport.protocolMessagesReceived.filter({ $0.action == .Connected }).last else { + guard let connectedMessage = transport.protocolMessagesReceived.filter({ $0.action == .connected }).last else { XCTFail("No CONNECTED protocol action received"); return } @@ -797,7 +797,7 @@ class Auth : QuickSpec { defer { realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Failed) { stateChange in + realtime.connection.once(.failed) { stateChange in expect(stateChange!.reason!.code).to(equal(40102)) expect(stateChange!.reason!.description).to(contain("incompatible credentials")) done() @@ -812,9 +812,10 @@ class Auth : QuickSpec { let rest = ARTRest(options: options) waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(ARTTokenParams(clientId: "wrong"), withOptions: nil) { tokenDetails, error in - expect(error!.code).to(equal(40102)) - expect(error!.description).to(contain("incompatible credentials")) + rest.auth.requestToken(ARTTokenParams(clientId: "wrong"), with: nil) { tokenDetails, error in + let error = error as! ARTErrorInfo + expect(error.code).to(equal(40102)) + expect(error.localizedDescription).to(contain("incompatible credentials")) expect(tokenDetails).to(beNil()) done() } @@ -838,9 +839,9 @@ class Auth : QuickSpec { waitUntil(timeout: testTimeout) { done in // Token - ARTRest(options: options).auth.requestToken(tokenParams, withOptions: options) { tokenDetails, error in + ARTRest(options: options).auth.requestToken(tokenParams, with: options) { tokenDetails, error in if let e = error { - XCTFail(e.description) + XCTFail((e as! ARTErrorInfo).description) } expect(tokenDetails?.capability).to(equal(tokenParams.capability)) done() @@ -862,24 +863,24 @@ class Auth : QuickSpec { waitUntil(timeout: testTimeout) { done in client.channels.get("test").publish(nil, data: "message") { error in if let e = error { - XCTFail(e.description) + XCTFail((e ).description) } done() } } switch extractBodyAsMsgPack(testHTTPExecutor.requests.last) { - case .Failure(let error): - XCTFail(error) - case .Success(let httpBody): - guard let requestedClientId = httpBody.unbox["clientId"] as? String else { XCTFail("No clientId field in HTTPBody"); return } + case .failure(let error): + XCTFail(error) + case .success(let httpBody): + guard let requestedClientId = httpBody.unbox["clientId"] as? String else { XCTFail("No clientId field in .tTPBody"); return } expect(requestedClientId).to(equal(expectedClientId)) } - // TODO: add more operations + // .oDO: add more operations } - // RSA7a2 + // .sA7a2 it("should obtain a token if clientId is assigned") { let options = AblyTests.setupOptions(AblyTests.jsonRestOptions) options.clientId = "client_string" @@ -890,7 +891,7 @@ class Auth : QuickSpec { waitUntil(timeout: testTimeout) { done in client.channels.get("test").publish(nil, data: "message") { error in if let e = error { - XCTFail(e.description) + XCTFail((e ).localizedDescription) } done() } @@ -915,7 +916,7 @@ class Auth : QuickSpec { options.clientId = "john" options.authCallback = { tokenParams, completion in expect(tokenParams.clientId).to(equal(options.clientId)) - completion(getTestToken(clientId: tokenParams.clientId), nil) + completion(getTestToken(clientId: tokenParams.clientId) as ARTTokenDetailsCompatible?, nil) } options.defaultTokenParams = ARTTokenParams(clientId: "tester") let client = ARTRest(options: options) @@ -926,7 +927,7 @@ class Auth : QuickSpec { channel.publish(nil, data: "message") { error in expect(error).to(beNil()) channel.history() { paginatedResult, error in - let message = paginatedResult!.items.first as! ARTMessage + let message = paginatedResult!.items.first! expect(message.clientId).to(equal("john")) done() } @@ -946,7 +947,7 @@ class Auth : QuickSpec { expect(realtime.auth.clientId).to(beNil()) waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange!.reason).to(beNil()) expect(realtime.auth.clientId).to(beNil()) done() @@ -955,7 +956,7 @@ class Auth : QuickSpec { let transport = realtime.transport as! TestProxyTransport transport.beforeProcessingReceivedMessage = { message in - if message.action == .Connected { + if message.action == .connected { if let details = message.connectionDetails { details.clientId = nil } @@ -974,11 +975,11 @@ class Auth : QuickSpec { expect(realtime.auth.clientId).to(beNil()) waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connecting) { stateChange in + realtime.connection.once(.connecting) { stateChange in expect(stateChange!.reason).to(beNil()) expect(realtime.auth.clientId).to(beNil()) } - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange!.reason).to(beNil()) expect(realtime.auth.clientId).to(equal("tester")) done() @@ -1013,7 +1014,7 @@ class Auth : QuickSpec { // Token client.auth.authorize(nil, options: nil) { token, error in expect(error).to(beNil()) - expect(client.auth.method).to(equal(ARTAuthMethod.Token)) + expect(client.auth.method).to(equal(ARTAuthMethod.token)) expect(client.auth.clientId).to(equal(options.clientId)) done() } @@ -1021,9 +1022,9 @@ class Auth : QuickSpec { // TokenRequest switch extractBodyAsMsgPack(testHTTPExecutor.requests.last) { - case .Failure(let error): + case .failure(let error): XCTFail(error) - case .Success(let httpBody): + case .success(let httpBody): guard let requestedClientId = httpBody.unbox["clientId"] as? String else { XCTFail("No clientId field in HTTPBody"); return } expect(client.auth.clientId).to(equal(requestedClientId)) } @@ -1039,12 +1040,12 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange!.reason).to(beNil()) expect(realtime.auth.clientId).to(equal("john")) let transport = realtime.transport as! TestProxyTransport - let connectedProtocolMessage = transport.protocolMessagesReceived.filter{ $0.action == .Connected }[0] + let connectedProtocolMessage = transport.protocolMessagesReceived.filter{ $0.action == .connected }[0] expect(connectedProtocolMessage.connectionDetails!.clientId).to(equal("john")) done() } @@ -1059,7 +1060,7 @@ class Auth : QuickSpec { let realtime = ARTRealtime(options: options) defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.on(.Connected) { _ in + realtime.connection.on(.connected) { _ in expect(realtime.auth.clientId).to(equal("*")) done() } @@ -1094,7 +1095,7 @@ class Auth : QuickSpec { let precedenceOptions = AblyTests.commonAppSetup() waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(tokenParams, withOptions: precedenceOptions) { tokenDetails, error in + rest.auth.requestToken(tokenParams, with: precedenceOptions) { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails).toNot(beNil()) expect(tokenDetails!.capability).to(equal("{\"cansubscribe:*\":[\"subscribe\"]}")) @@ -1112,12 +1113,12 @@ class Auth : QuickSpec { precedenceOptions2.clientId = nil waitUntil(timeout: testTimeout) { done in - rest2.auth.requestToken(nil, withOptions: precedenceOptions2) { tokenDetails, error in + rest2.auth.requestToken(nil, with: precedenceOptions2) { tokenDetails, error in expect(error).to(beNil()) - guard let aTokenDetails = tokenDetails else { + guard let tokenDetails = tokenDetails else { XCTFail("tokenDetails is nil"); done(); return } - expect(aTokenDetails.clientId).to(beNil()) + expect(tokenDetails.clientId).to(beNil()) done() } } @@ -1130,7 +1131,7 @@ class Auth : QuickSpec { let rest = ARTRest(options: options) waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(nil, withOptions: nil) { tokenDetails, error in + rest.auth.requestToken(nil, with: nil) { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails).toNot(beNil()) expect(tokenDetails!.capability).to(equal("{\"*\":[\"*\"]}")) @@ -1149,7 +1150,7 @@ class Auth : QuickSpec { // Provide TokenParams and Options waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(tokenParams, withOptions: authOptions) { tokenDetails, error in + rest.auth.requestToken(tokenParams, with: authOptions) { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails).toNot(beNil()) expect(tokenDetails!.capability).to(equal("{\"cansubscribe:*\":[\"subscribe\"]}")) @@ -1161,7 +1162,7 @@ class Auth : QuickSpec { // Provide TokenParams as null waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(nil, withOptions: authOptions) { tokenDetails, error in + rest.auth.requestToken(nil, with: authOptions) { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails).toNot(beNil()) expect(tokenDetails!.capability).to(equal("{\"*\":[\"*\"]}")) @@ -1191,19 +1192,19 @@ class Auth : QuickSpec { let testToken = getTestToken() let options = ARTClientOptions() - options.authUrl = NSURL(string: "http://echo.ably.io") + options.authUrl = NSURL(string: "http://echo.ably.io") as URL? expect(options.authUrl).toNot(beNil()) // Plain text - options.authParams = [NSURLQueryItem]() - options.authParams!.append(NSURLQueryItem(name: "type", value: "text")) - options.authParams!.append(NSURLQueryItem(name: "body", value: testToken)) + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams!.append(NSURLQueryItem(name: "type", value: "text") as URLQueryItem) + options.authParams!.append(NSURLQueryItem(name: "body", value: testToken) as URLQueryItem) let rest = ARTRest(options: options) rest.httpExecutor = testHTTPExecutor waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(nil, withOptions: nil, callback: { tokenDetails, error in - expect(testHTTPExecutor.requests.last?.URL?.host).to(equal("echo.ably.io")) + rest.auth.requestToken(nil, with: nil, callback: { tokenDetails, error in + expect(testHTTPExecutor.requests.last?.url?.host).to(equal("echo.ably.io")) expect(error).to(beNil()) expect(tokenDetails).toNot(beNil()) expect(tokenDetails?.token).to(equal(testToken)) @@ -1220,25 +1221,25 @@ class Auth : QuickSpec { let encoder = ARTJsonLikeEncoder() encoder.delegate = ARTJsonEncoder() - guard let jsonTokenDetails = try? encoder.encodeTokenDetails(testTokenDetails) else { + guard let jsonTokenDetails = try? encoder.encode(testTokenDetails) else { fail("Invalid TokenDetails") return } let options = ARTClientOptions() - options.authUrl = NSURL(string: "http://echo.ably.io") + options.authUrl = NSURL(string: "http://echo.ably.io") as URL? expect(options.authUrl).toNot(beNil()) // JSON with TokenDetails - options.authParams = [NSURLQueryItem]() - options.authParams?.append(NSURLQueryItem(name: "type", value: "json")) - options.authParams?.append(NSURLQueryItem(name: "body", value: jsonTokenDetails.toUTF8String)) + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams?.append(NSURLQueryItem(name: "type", value: "json") as URLQueryItem) + options.authParams?.append(NSURLQueryItem(name: "body", value: jsonTokenDetails.toUTF8String) as URLQueryItem) let rest = ARTRest(options: options) rest.httpExecutor = testHTTPExecutor waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(nil, withOptions: nil, callback: { tokenDetails, error in - expect(testHTTPExecutor.requests.last?.URL?.host).to(equal("echo.ably.io")) + rest.auth.requestToken(nil, with: nil, callback: { tokenDetails, error in + expect(testHTTPExecutor.requests.last?.url?.host).to(equal("echo.ably.io")) expect(error).to(beNil()) expect(tokenDetails).toNot(beNil()) expect(tokenDetails?.clientId) == testTokenDetails.clientId @@ -1246,10 +1247,10 @@ class Auth : QuickSpec { expect(tokenDetails?.issued).toNot(beNil()) expect(tokenDetails?.expires).toNot(beNil()) if let issued = tokenDetails?.issued, let testIssued = testTokenDetails.issued { - expect(issued.compare(testIssued)) == NSComparisonResult.OrderedSame + expect(issued.compare(testIssued)) == ComparisonResult.orderedSame } if let expires = tokenDetails?.expires, let testExpires = testTokenDetails.expires { - expect(expires.compare(testExpires)) == NSComparisonResult.OrderedSame + expect(expires.compare(testExpires)) == ComparisonResult.orderedSame } done() }) @@ -1261,7 +1262,7 @@ class Auth : QuickSpec { tokenParams.capability = "{\"test\":[\"subscribe\"]}" let options = AblyTests.commonAppSetup() - options.authUrl = NSURL(string: "http://echo.ably.io") + options.authUrl = NSURL(string: "http://echo.ably.io") as URL? expect(options.authUrl).toNot(beNil()) var rest = ARTRest(options: options) @@ -1283,23 +1284,23 @@ class Auth : QuickSpec { let encoder = ARTJsonLikeEncoder() encoder.delegate = ARTJsonEncoder() - guard let jsonTokenRequest = try? encoder.encodeTokenRequest(testTokenRequest) else { + guard let jsonTokenRequest = try? encoder.encode(testTokenRequest) else { fail("Invalid TokenRequest") return } // JSON with TokenRequest - options.authParams = [NSURLQueryItem]() - options.authParams?.append(NSURLQueryItem(name: "type", value: "json")) - options.authParams?.append(NSURLQueryItem(name: "body", value: jsonTokenRequest.toUTF8String)) + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams?.append(NSURLQueryItem(name: "type", value: "json") as URLQueryItem) + options.authParams?.append(NSURLQueryItem(name: "body", value: jsonTokenRequest.toUTF8String) as URLQueryItem) rest = ARTRest(options: options) rest.httpExecutor = testHTTPExecutor waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(nil, withOptions: nil, callback: { tokenDetails, error in - expect(testHTTPExecutor.requests.first?.URL?.host).to(equal("echo.ably.io")) - expect(testHTTPExecutor.requests.last?.URL?.host).toNot(equal("echo.ably.io")) + rest.auth.requestToken(nil, with: nil, callback: { tokenDetails, error in + expect(testHTTPExecutor.requests.first?.url?.host).to(equal("echo.ably.io")) + expect(testHTTPExecutor.requests.last?.url?.host).toNot(equal("echo.ably.io")) expect(error).to(beNil()) guard let tokenDetails = tokenDetails else { fail("TokenDetails is empty"); done() @@ -1316,21 +1317,21 @@ class Auth : QuickSpec { // RSA8c1a it("should be added to the URL when auth method is GET") { let clientOptions = ARTClientOptions() - clientOptions.authUrl = NSURL(string: "http://auth.ably.io") + clientOptions.authUrl = NSURL(string: "http://auth.ably.io") as URL? var authParams = [ "param1": "value", "param2": "value", "clientId": "should not be overwritten", ] clientOptions.authParams = authParams.map { - NSURLQueryItem(name: $0, value: $1) + NSURLQueryItem(name: $0, value: $1) as URLQueryItem } clientOptions.authHeaders = ["X-Header-1": "foo", "X-Header-2": "bar"] let tokenParams = ARTTokenParams() tokenParams.clientId = "test" let rest = ARTRest(options: clientOptions) - let request = rest.auth.buildRequest(clientOptions, withParams: tokenParams) + let request = rest.auth.buildRequest(clientOptions, with: tokenParams) for (header, expectedValue) in clientOptions.authHeaders! { if let value = request.allHTTPHeaderFields?[header] { @@ -1340,11 +1341,11 @@ class Auth : QuickSpec { } } - guard let url = request.URL else { + guard let url = request.url else { fail("Request is invalid") return } - guard let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) else { + guard let urlComponents = NSURLComponents(url: url, resolvingAgainstBaseURL: false) else { fail("invalid URL: \(url)") return } @@ -1360,7 +1361,7 @@ class Auth : QuickSpec { expectedValue = "test" } expect(queryItem.value!).to(equal(expectedValue)) - authParams.removeValueForKey(queryItem.name) + authParams.removeValue(forKey: queryItem.name) } } expect(authParams).to(beEmpty()) @@ -1369,23 +1370,23 @@ class Auth : QuickSpec { // RSA8c1b it("should added on the body request when auth method is POST") { let clientOptions = ARTClientOptions() - clientOptions.authUrl = NSURL(string: "http://auth.ably.io") + clientOptions.authUrl = NSURL(string: "http://auth.ably.io") as URL? clientOptions.authMethod = "POST" clientOptions.authHeaders = ["X-Header-1": "foo", "X-Header-2": "bar"] let tokenParams = ARTTokenParams() let rest = ARTRest(options: clientOptions) - let request = rest.auth.buildRequest(clientOptions, withParams: tokenParams) + let request = rest.auth.buildRequest(clientOptions, with: tokenParams) - let httpBodyJSON = try! NSJSONSerialization.JSONObjectWithData(request.HTTPBody ?? NSData(), options: .MutableLeaves) as? NSDictionary + let httpBodyJSON = try! JSONSerialization.jsonObject(with: request.httpBody ?? NSData() as Data, options: .mutableLeaves) as? NSDictionary expect(httpBodyJSON).toNot(beNil(), description: "HTTPBody is empty") expect(httpBodyJSON!["timestamp"]).toNot(beNil(), description: "HTTPBody has no timestamp") let expectedJSON = ["ttl":NSString(format: "%f", CGFloat(60*60)), "capability":"{\"*\":[\"*\"]}", "timestamp":httpBodyJSON!["timestamp"]!] - expect(httpBodyJSON) == expectedJSON + expect(httpBodyJSON) == expectedJSON as NSDictionary for (header, expectedValue) in clientOptions.authHeaders! { if let value = request.allHTTPHeaderFields?[header] { @@ -1401,14 +1402,14 @@ class Auth : QuickSpec { it("TokenParams should take precedence over any configured authParams when a name conflict occurs") { let options = ARTClientOptions() options.clientId = "john" - options.authUrl = NSURL(string: "http://auth.ably.io") + options.authUrl = NSURL(string: "http://auth.ably.io") as URL? options.authMethod = "GET" options.authHeaders = ["X-Header-1": "foo1", "X-Header-2": "foo2"] let authParams = [ "key": "secret", "clientId": "should be overridden" ] - options.authParams = authParams.map { NSURLQueryItem(name: $0, value: $1) } + options.authParams = authParams.map { NSURLQueryItem(name: $0, value: $1) as URLQueryItem } let tokenParams = ARTTokenParams() tokenParams.clientId = "tester" @@ -1417,8 +1418,8 @@ class Auth : QuickSpec { client.httpExecutor = testHTTPExecutor waitUntil(timeout: testTimeout) { done in - client.auth.requestToken(tokenParams, withOptions: nil) { tokenDetails, error in - let query = testHTTPExecutor.requests[0].URL!.query + client.auth.requestToken(tokenParams, with: nil) { tokenDetails, error in + let query = testHTTPExecutor.requests[0].url!.query expect(query).to(haveParam("clientId", withValue: tokenParams.clientId!)) done() } @@ -1428,15 +1429,14 @@ class Auth : QuickSpec { // RSA8c3 it("should override previously configured parameters") { let clientOptions = ARTClientOptions() - clientOptions.authUrl = NSURL(string: "http://auth.ably.io") + clientOptions.authUrl = NSURL(string: "http://auth.ably.io") as URL? let rest = ARTRest(options: clientOptions) let authOptions = ARTAuthOptions() - authOptions.authUrl = NSURL(string: "http://auth.ably.io") - authOptions.authParams = [NSURLQueryItem(name: "ttl", value: "invalid")] - authOptions.authParams = [NSURLQueryItem(name: "test", value: "1")] - - let url = rest.auth.buildURL(authOptions, withParams: ARTTokenParams()) + authOptions.authUrl = NSURL(string: "http://auth.ably.io") as URL? + authOptions.authParams = [NSURLQueryItem(name: "ttl", value: "invalid") as URLQueryItem] + authOptions.authParams = [NSURLQueryItem(name: "test", value: "1") as URLQueryItem] + let url = rest.auth.buildURL(authOptions, with: ARTTokenParams()) expect(url.absoluteString).to(contain(NSURL(string: "http://auth.ably.io")?.absoluteString ?? "")) } } @@ -1446,14 +1446,15 @@ class Auth : QuickSpec { let rest = ARTRest(options: AblyTests.commonAppSetup()) var createTokenRequestMethodWasCalled = false + // Adds a block of code after `createTokenRequest` is triggered - let token = rest.auth.testSuite_injectIntoMethodAfter(NSSelectorFromString("_createTokenRequest:options:callback:")) { + let token = rest.auth.testSuite_injectIntoMethod(after: NSSelectorFromString("_createTokenRequest:options:callback:")) { createTokenRequestMethodWasCalled = true } defer { token.remove() } waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(nil, withOptions: nil, callback: { tokenDetails, error in + rest.auth.requestToken(nil, with: nil, callback: { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails?.token).toNot(beEmpty()) done() @@ -1477,13 +1478,13 @@ class Auth : QuickSpec { let defaultTokenParams = ARTTokenParams(clientId: currentClientId) waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(nil, withOptions: nil, callback: { tokenDetails, error in + rest.auth.requestToken(nil, with: nil, callback: { tokenDetails, error in expect(tokenDetails?.clientId).to(equal(defaultTokenParams.clientId)) expect(tokenDetails?.capability).to(equal(defaultTokenParams.capability)) expect(tokenDetails?.issued).toNot(beNil()) expect(tokenDetails?.expires).toNot(beNil()) if let issued = tokenDetails?.issued, let expires = tokenDetails?.expires { - expect(expires.timeIntervalSinceDate(issued)).to(equal(defaultTokenParams.ttl)) + expect(expires.timeIntervalSince(issued)).to(equal(defaultTokenParams.ttl)) } done() }) @@ -1500,14 +1501,14 @@ class Auth : QuickSpec { tokenParams.capability = expectedCapability waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(tokenParams, withOptions: nil, callback: { tokenDetails, error in + rest.auth.requestToken(tokenParams, with: nil, callback: { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails?.clientId).to(equal(options.clientId)) expect(tokenDetails?.capability).to(equal(expectedCapability)) expect(tokenDetails?.issued).toNot(beNil()) expect(tokenDetails?.expires).toNot(beNil()) if let issued = tokenDetails?.issued, let expires = tokenDetails?.expires { - expect(expires.timeIntervalSinceDate(issued)).to(equal(expectedTtl)) + expect(expires.timeIntervalSince(issued)).to(equal(expectedTtl)) } done() }) @@ -1524,11 +1525,11 @@ class Auth : QuickSpec { options.authCallback = { tokenParams, completion in expect(tokenParams.clientId).to(beNil()) - completion("token_string", nil) + completion("token_string" as ARTTokenDetailsCompatible?, nil) } waitUntil(timeout: testTimeout) { done in - ARTRest(options: options).auth.requestToken(expectedTokenParams, withOptions: nil) { tokenDetails, error in + ARTRest(options: options).auth.requestToken(expectedTokenParams, with: nil) { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails!.token).to(equal("token_string")) done() @@ -1546,7 +1547,7 @@ class Auth : QuickSpec { } waitUntil(timeout: testTimeout) { done in - ARTRest(options: options).auth.requestToken(expectedTokenParams, withOptions: nil) { tokenDetails, error in + ARTRest(options: options).auth.requestToken(expectedTokenParams, with: nil) { tokenDetails, error in expect(error).to(beNil()) expect(tokenDetails!.token).to(equal("token_from_details")) done() @@ -1570,7 +1571,7 @@ class Auth : QuickSpec { rest = ARTRest(options: options) waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(expectedTokenParams, withOptions: nil) { tokenDetails, error in + rest.auth.requestToken(expectedTokenParams, with: nil) { tokenDetails, error in expect(error).to(beNil()) guard let tokenDetails = tokenDetails else { fail("tokenDetails is nil"); done(); return @@ -1596,15 +1597,15 @@ class Auth : QuickSpec { channel.publish([message]) { error in expect(error).to(beNil()) switch extractBodyAsMessages(testHTTPExecutor.requests.first) { - case .Failure(let error): + case .failure(let error): fail(error) - case .Success(let httpBody): + case .success(let httpBody): expect(httpBody.unbox.first!["clientId"]).to(beNil()) } channel.history { page, error in expect(error).to(beNil()) expect(page!.items).to(haveCount(1)) - expect((page!.items[0] as! ARTMessage).clientId).to(beNil()) + expect((page!.items[0] ).clientId).to(beNil()) done() } } @@ -1653,15 +1654,15 @@ class Auth : QuickSpec { channel.publish([message]) { error in expect(error).to(beNil()) switch extractBodyAsMessages(testHTTPExecutor.requests.first) { - case .Failure(let error): + case .failure(let error): fail(error) - case .Success(let httpBody): + case .success(let httpBody): expect(httpBody.unbox.first!["clientId"]).to(beNil()) } channel.history { page, error in expect(error).to(beNil()) expect(page!.items).to(haveCount(1)) - expect((page!.items[0] as! ARTMessage).clientId).to(beNil()) + expect((page!.items[0] ).clientId).to(beNil()) done() } } @@ -1683,7 +1684,7 @@ class Auth : QuickSpec { expect(error).to(beNil()) channel.history { page, error in expect(error).to(beNil()) - let item = page!.items[0] as! ARTMessage + let item = page!.items[0] expect(item.clientId).to(equal("john")) done() } @@ -1727,11 +1728,11 @@ class Auth : QuickSpec { authOptions.queryTime = true authOptions.key = options.key - let mockServerDate = NSDate().dateByAddingTimeInterval(120) - rest.auth.testSuite_returnValueFor(NSSelectorFromString("handleServerTime:"), withDate: mockServerDate) + let mockServerDate = NSDate().addingTimeInterval(120) + rest.auth.testSuite_returnValue(for: NSSelectorFromString("handleServerTime:"), with: mockServerDate as Date) var serverTimeRequestCount = 0 - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time(_:))) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time(_:))) { serverTimeRequestCount += 1 } defer { hook.remove() } @@ -1850,7 +1851,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(error.description).to(contain("no key provided for signing token requests")) + expect(error.localizedDescription).to(contain("no key provided for signing token requests")) done() } } @@ -1871,7 +1872,7 @@ class Auth : QuickSpec { authOptions.key = options.key var serverTimeRequestCount = 0 - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time(_:))) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time(_:))) { serverTimeRequestCount += 1 } defer { hook.remove() } @@ -1916,7 +1917,7 @@ class Auth : QuickSpec { guard let tokenRequest = tokenRequest else { XCTFail("TokenRequest is nil"); return } - expect(tokenRequest).to(beAnInstanceOf(ARTTokenRequest)) + expect(tokenRequest).to(beAnInstanceOf(ARTTokenRequest.self)) expect(tokenRequest.clientId).to(equal(expectedClientId)) expect(tokenRequest.mac).toNot(beNil()) expect(tokenRequest.nonce).toNot(beNil()) @@ -1991,9 +1992,9 @@ class Auth : QuickSpec { serverTimeRequestWasMade = true } - let hook = ARTRest.aspect_hookSelector(rest) + let hook = ARTRest.aspect_hook(rest) // Adds a block of code after `time` is triggered - let _ = try? hook(#selector(ARTRest.time(_:)), withOptions: .PositionAfter, usingBlock: unsafeBitCast(block, ARTRest.self)) + let _ = try? hook(#selector(ARTRest.time(_:)), .positionBefore, unsafeBitCast(block, to: ARTRest.self)) let authOptions = ARTAuthOptions() authOptions.queryTime = true @@ -2031,7 +2032,7 @@ class Auth : QuickSpec { let tokenParams = ARTTokenParams() expect(tokenParams.ttl).to(equal(ARTDefault.ttl())) - let expectedTtl = NSTimeInterval(10) + let expectedTtl = TimeInterval(10) tokenParams.ttl = expectedTtl rest.auth.createTokenRequest(tokenParams, options: nil, callback: { tokenRequest, error in @@ -2054,10 +2055,10 @@ class Auth : QuickSpec { expect(tokenRequest.ttl).to(equal(ARTDefault.ttl())) // Check if the encoder changes the TTL to milliseconds let encoder = rest.defaultEncoder as! ARTJsonLikeEncoder - let data = try! encoder.encodeTokenRequest(tokenRequest) + let data = try! encoder.encode(tokenRequest) let jsonObject = (try! encoder.delegate!.decode(data)) as! NSDictionary let ttl = jsonObject["ttl"] as! NSNumber - expect(ttl).to(equal(60 * 60 * 1000)) + expect(ttl as? Decimal).to(equal(60 * 60 * 1000)) }) } @@ -2067,13 +2068,13 @@ class Auth : QuickSpec { tokenParams.ttl *= 24 waitUntil(timeout: testTimeout) { done in - rest.auth.requestToken(tokenParams, withOptions: nil) { tokenDetails, error in + rest.auth.requestToken(tokenParams, with: nil) { tokenDetails, error in expect(error).to(beNil()) guard let tokenDetails = tokenDetails else { XCTFail("TokenDetails is nil"); done(); return } let dayInSeconds = 24 * 60 * 60 - expect(tokenDetails.expires!.timeIntervalSinceDate(tokenDetails.issued!)).to(beCloseTo(dayInSeconds)) + expect(tokenDetails.expires!.timeIntervalSince(tokenDetails.issued!)).to(beCloseTo(Double(dayInSeconds))) done() } } @@ -2089,10 +2090,10 @@ class Auth : QuickSpec { tokenParams.capability = "{ - }" rest.auth.createTokenRequest(tokenParams, options: nil, callback: { tokenRequest, error in - guard let error = error else { + guard let error = error as? ARTErrorInfo else { XCTFail("Error is nil"); return } - expect(error.description).to(contain("Capability")) + expect(error.localizedDescription).to(contain("Capability")) expect(tokenRequest?.capability).to(beNil()) }) @@ -2121,7 +2122,7 @@ class Auth : QuickSpec { XCTFail("TokenRequest is nil"); done(); return } let signed = tokenParams.sign(rest.options.key!, withNonce: tokenRequest1.nonce) - expect(tokenRequest1.mac).to(equal(signed.mac)) + expect(tokenRequest1.mac).to(equal(signed?.mac)) rest.auth.createTokenRequest(tokenParams, options: nil, callback: { tokenRequest, error in expect(error).to(beNil()) @@ -2153,7 +2154,7 @@ class Auth : QuickSpec { var serverTime: NSDate? waitUntil(timeout: testTimeout) { done in rest.time({ date, error in - serverTime = date + serverTime = date as NSDate? done() }) } @@ -2193,7 +2194,7 @@ class Auth : QuickSpec { } // Check that token exists - expect(rest.auth.method).to(equal(ARTAuthMethod.Token)) + expect(rest.auth.method).to(equal(ARTAuthMethod.token)) guard let firstTokenDetails = rest.auth.tokenDetails else { fail("TokenDetails is nil"); return } @@ -2207,7 +2208,7 @@ class Auth : QuickSpec { } // Check that token has not changed - expect(rest.auth.method).to(equal(ARTAuthMethod.Token)) + expect(rest.auth.method).to(equal(ARTAuthMethod.token)) guard let secondTokenDetails = rest.auth.tokenDetails else { fail("TokenDetails is nil"); return } @@ -2248,11 +2249,11 @@ class Auth : QuickSpec { XCTFail("TokenDetails is nil"); done(); return } expect(tokenDetails.token).toNot(equal(testToken)) - expect(rest.auth.method).to(equal(ARTAuthMethod.Token)) + expect(rest.auth.method).to(equal(ARTAuthMethod.token)) publishTestMessage(rest, completion: { error in expect(error).to(beNil()) - expect(rest.auth.method).to(equal(ARTAuthMethod.Token)) + expect(rest.auth.method).to(equal(ARTAuthMethod.token)) expect(rest.auth.tokenDetails?.token).to(equal(tokenDetails.token)) done() }) @@ -2272,11 +2273,11 @@ class Auth : QuickSpec { XCTFail("TokenDetails is nil"); done(); return } expect(tokenDetails.token).toNot(beNil()) - expect(rest.auth.method).to(equal(ARTAuthMethod.Token)) + expect(rest.auth.method).to(equal(ARTAuthMethod.token)) publishTestMessage(rest, completion: { error in expect(error).to(beNil()) - expect(rest.auth.method).to(equal(ARTAuthMethod.Token)) + expect(rest.auth.method).to(equal(ARTAuthMethod.token)) expect(rest.auth.tokenDetails?.token).to(equal(tokenDetails.token)) done() }) @@ -2290,10 +2291,10 @@ class Auth : QuickSpec { waitUntil(timeout: testTimeout) { done in rest.auth.authorize(ARTTokenParams(), options: ARTAuthOptions(), callback: { tokenDetails, error in - guard let error = error else { + guard let error = error as? ARTErrorInfo else { fail("Error is nil"); done(); return } - expect(error.description).to(contain("no means to renew the token is provided")) + expect(error.localizedDescription).to(contain("no means to renew the token is provided")) done() }) } @@ -2308,9 +2309,9 @@ class Auth : QuickSpec { requestMethodWasCalled = true } - let hook = ARTAuth.aspect_hookSelector(rest.auth) + let hook = ARTAuth.aspect_hook(rest.auth) // Adds a block of code after `requestToken` is triggered - let token = try? hook(#selector(ARTAuth.requestToken(_:withOptions:callback:)), withOptions: .PositionAfter, usingBlock: unsafeBitCast(block, ARTAuth.self)) + let token = try? hook(#selector(ARTAuth.requestToken(_:with:callback:)), [], unsafeBitCast(block, to: ARTAuth.self)) expect(token).toNot(beNil()) @@ -2340,7 +2341,7 @@ class Auth : QuickSpec { guard let tokenDetails = tokenDetails else { XCTFail("TokenDetails is nil"); done(); return } - expect(tokenDetails).to(beAnInstanceOf(ARTTokenDetails)) + expect(tokenDetails).to(beAnInstanceOf(ARTTokenDetails.self)) expect(tokenDetails.token).toNot(beEmpty()) expect(tokenDetails.expires!.timeIntervalSinceNow).to(beGreaterThan(tokenDetails.issued!.timeIntervalSinceNow)) expect(tokenDetails.clientId).to(equal(options.clientId)) @@ -2360,10 +2361,10 @@ class Auth : QuickSpec { let token = getTestToken() let authOptions = ARTAuthOptions() // Use authUrl for authentication with plain text token response - authOptions.authUrl = NSURL(string: "http://echo.ably.io")! - authOptions.authParams = [NSURLQueryItem]() - authOptions.authParams?.append(NSURLQueryItem(name: "type", value: "text")) - authOptions.authParams?.append(NSURLQueryItem(name: "body", value: token)) + authOptions.authUrl = NSURL(string: "http://echo.ably.io")! as URL + authOptions.authParams = [NSURLQueryItem]() as [URLQueryItem]? + authOptions.authParams?.append(NSURLQueryItem(name: "type", value: "text") as URLQueryItem) + authOptions.authParams?.append(NSURLQueryItem(name: "body", value: token) as URLQueryItem) authOptions.authHeaders = ["X-Ably":"Test"] authOptions.queryTime = true @@ -2382,7 +2383,7 @@ class Auth : QuickSpec { guard let tokenDetails = tokenDetails else { XCTFail("TokenDetails is nil"); done(); return } - expect(testHTTPExecutor.requests.last?.URL?.host).to(equal("echo.ably.io")) + expect(testHTTPExecutor.requests.last?.url?.host).to(equal("echo.ably.io")) expect(auth.options.authUrl!.host).to(equal("echo.ably.io")) expect(auth.options.authHeaders!["X-Ably"]).to(equal("Test")) expect(tokenDetails.token).to(equal(token)) @@ -2434,7 +2435,7 @@ class Auth : QuickSpec { authOptions.queryTime = true var serverTimeRequestWasMade = false - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time(_:))) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time(_:))) { serverTimeRequestWasMade = true } defer { hook.remove() } @@ -2484,7 +2485,7 @@ class Auth : QuickSpec { XCTFail("TokenDetails is nil"); done(); return } expect(tokenDetails.clientId).to(equal(ExpectedTokenParams.clientId)) - expect(tokenDetails.issued!.dateByAddingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires)) + expect(tokenDetails.issued!.addingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires!)) expect(tokenDetails.capability).to(equal(ExpectedTokenParams.capability)) done() } @@ -2582,10 +2583,10 @@ class Auth : QuickSpec { guard let tokenDetails = tokenDetails else { XCTFail("TokenDetails is nil"); done(); return } - expect(tokenDetails).to(beAnInstanceOf(ARTTokenDetails)) + expect(tokenDetails).to(beAnInstanceOf(ARTTokenDetails.self)) expect(tokenDetails.token).toNot(beEmpty()) expect(tokenDetails.clientId).to(equal(ExpectedTokenParams.clientId)) - expect(tokenDetails.issued!.dateByAddingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires)) + expect(tokenDetails.issued!.addingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires!)) expect(tokenDetails.capability).to(equal(ExpectedTokenParams.capability)) done() } @@ -2616,7 +2617,7 @@ class Auth : QuickSpec { guard let tokenDetails = tokenDetails else { XCTFail("TokenDetails is nil"); done(); return } - expect(tokenDetails).to(beAnInstanceOf(ARTTokenDetails)) + expect(tokenDetails).to(beAnInstanceOf(ARTTokenDetails.self)) expect(tokenDetails.token).toNot(beEmpty()) expect(tokenDetails.expires!.timeIntervalSinceNow).to(beGreaterThan(tokenDetails.issued!.timeIntervalSinceNow)) done() @@ -2626,7 +2627,7 @@ class Auth : QuickSpec { it("authUrl") { let options = ARTClientOptions() - options.authUrl = NSURL(string: "http://echo.ably.io")! + options.authUrl = NSURL(string: "http://echo.ably.io")! as URL waitUntil(timeout: testTimeout) { done in ARTRest(options: options).auth.authorize(nil, options: nil) { tokenDetails, error in @@ -2648,17 +2649,17 @@ class Auth : QuickSpec { let encoder = ARTJsonLikeEncoder() encoder.delegate = ARTJsonEncoder() - guard let tokenDetailsJSON = NSString(data: try! encoder.encodeTokenDetails(tokenDetails), encoding: NSUTF8StringEncoding) else { + guard let tokenDetailsJSON = String(data: try! encoder.encode(tokenDetails), encoding: .utf8) else { XCTFail("JSON TokenDetails is empty") return } let options = ARTClientOptions() // Use authUrl for authentication with JSON TokenDetails response - options.authUrl = NSURL(string: "http://echo.ably.io")! - options.authParams = [NSURLQueryItem]() - options.authParams?.append(NSURLQueryItem(name: "type", value: "json")) - options.authParams?.append(NSURLQueryItem(name: "body", value: "[]")) + options.authUrl = NSURL(string: "http://echo.ably.io")! as URL + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams?.append(NSURLQueryItem(name: "type", value: "json") as URLQueryItem) + options.authParams?.append(NSURLQueryItem(name: "body", value: "[]") as URLQueryItem) // Invalid TokenDetails waitUntil(timeout: testTimeout) { done in @@ -2666,14 +2667,14 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(error.code).to(equal(Int(ARTState.AuthUrlIncompatibleContent.rawValue))) + expect((error as! ARTErrorInfo).code).to(equal(Int(ARTState.authUrlIncompatibleContent.rawValue))) expect(tokenDetails).to(beNil()) done() } } options.authParams?.removeLast() - options.authParams?.append(NSURLQueryItem(name: "body", value: tokenDetailsJSON as String)) + options.authParams?.append(NSURLQueryItem(name: "body", value: tokenDetailsJSON as String) as URLQueryItem) // Valid token waitUntil(timeout: testTimeout) { done in @@ -2689,10 +2690,10 @@ class Auth : QuickSpec { let token = getTestToken() let options = ARTClientOptions() // Use authUrl for authentication with plain text token response - options.authUrl = NSURL(string: "http://echo.ably.io")! - options.authParams = [NSURLQueryItem]() - options.authParams?.append(NSURLQueryItem(name: "type", value: "text")) - options.authParams?.append(NSURLQueryItem(name: "body", value: "")) + options.authUrl = NSURL(string: "http://echo.ably.io")! as URL + options.authParams = [NSURLQueryItem]() as [URLQueryItem]? + options.authParams?.append(NSURLQueryItem(name: "type", value: "text") as URLQueryItem) + options.authParams?.append(NSURLQueryItem(name: "body", value: "") as URLQueryItem) // Invalid token waitUntil(timeout: testTimeout) { done in @@ -2704,7 +2705,7 @@ class Auth : QuickSpec { } options.authParams?.removeLast() - options.authParams?.append(NSURLQueryItem(name: "body", value: token)) + options.authParams?.append(NSURLQueryItem(name: "body", value: token) as URLQueryItem) // Valid token waitUntil(timeout: testTimeout) { done in @@ -2754,7 +2755,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(error.description).to(contain("no means to renew the token")) + expect(error.localizedDescription).to(contain("no means to renew the token")) done() } } @@ -2765,7 +2766,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(error.description).to(contain("no means to renew the token")) + expect(error.localizedDescription).to(contain("no means to renew the token")) done() } } @@ -2777,16 +2778,16 @@ class Auth : QuickSpec { let testTokenDetails = getTestTokenDetails(ttl: 0.1) let encoder = ARTJsonLikeEncoder() encoder.delegate = ARTJsonEncoder() - guard let currentTokenDetails = testTokenDetails, jsonTokenDetails = try? encoder.encodeTokenDetails(currentTokenDetails) else { + guard let currentTokenDetails = testTokenDetails, let jsonTokenDetails = try? encoder.encode(currentTokenDetails) else { fail("Invalid TokenDetails") return } let authOptions = ARTAuthOptions() - authOptions.authUrl = NSURL(string: "http://echo.ably.io")! - authOptions.authParams = [NSURLQueryItem]() - authOptions.authParams?.append(NSURLQueryItem(name: "type", value: "json")) - authOptions.authParams?.append(NSURLQueryItem(name: "body", value: jsonTokenDetails.toUTF8String)) + authOptions.authUrl = NSURL(string: "http://echo.ably.io")! as URL + authOptions.authParams = [NSURLQueryItem]() as [URLQueryItem]? + authOptions.authParams?.append(NSURLQueryItem(name: "type", value: "json") as URLQueryItem) + authOptions.authParams?.append(NSURLQueryItem(name: "body", value: jsonTokenDetails.toUTF8String) as URLQueryItem) authOptions.authHeaders = ["X-Ably":"Test"] waitUntil(timeout: testTimeout) { done in @@ -2840,7 +2841,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(UInt(error.code)).to(equal(ARTState.RequestTokenFailed.rawValue)) + expect(UInt((error as! ARTErrorInfo).code)).to(equal(ARTState.requestTokenFailed.rawValue)) expect(tokenDetails).to(beNil()) expect(rest.auth.options.authUrl).to(beNil()) expect(rest.auth.options.authParams).to(beNil()) @@ -2855,7 +2856,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(UInt(error.code)).to(equal(ARTState.RequestTokenFailed.rawValue)) + expect(UInt((error as! ARTErrorInfo).code)).to(equal(ARTState.requestTokenFailed.rawValue)) expect(tokenDetails).to(beNil()) expect(rest.auth.options.authUrl).to(beNil()) expect(rest.auth.options.authParams).to(beNil()) @@ -2868,7 +2869,7 @@ class Auth : QuickSpec { it("should supersede configured AuthOptions (using authCallback) even if arguments objects are empty") { let rest = ARTRest(options: AblyTests.commonAppSetup()) - let testTokenDetails = ARTTokenDetails(token: "token", expires: NSDate(), issued: NSDate(), capability: nil, clientId: nil) + let testTokenDetails = ARTTokenDetails(token: "token", expires: NSDate() as Date, issued: NSDate() as Date, capability: nil, clientId: nil) var authCallbackHasBeenInvoked = false let authOptions = ARTAuthOptions() authOptions.authCallback = { tokenParams, completion in @@ -2904,7 +2905,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(UInt(error.code)).to(equal(ARTState.RequestTokenFailed.rawValue)) + expect(UInt((error as! ARTErrorInfo).code)).to(equal(ARTState.requestTokenFailed.rawValue)) expect(tokenDetails).to(beNil()) expect(authCallbackHasBeenInvoked).to(beFalse()) expect(rest.auth.options.authCallback).to(beNil()) @@ -2917,7 +2918,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(UInt(error.code)).to(equal(ARTState.RequestTokenFailed.rawValue)) + expect(UInt((error as! ARTErrorInfo).code)).to(equal(ARTState.requestTokenFailed.rawValue)) expect(tokenDetails).to(beNil()) expect(authCallbackHasBeenInvoked).to(beFalse()) expect(rest.auth.options.authCallback).to(beNil()) @@ -2942,7 +2943,7 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(error.code).to(equal(40400)) + expect((error as! ARTErrorInfo).code).to(equal(40400)) expect(tokenDetails).to(beNil()) done() } @@ -2958,7 +2959,7 @@ class Auth : QuickSpec { authOptions.queryTime = true var serverTimeRequestCount = 0 - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time(_:))) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time(_:))) { serverTimeRequestCount += 1 } defer { hook.remove() } @@ -2970,7 +2971,7 @@ class Auth : QuickSpec { XCTFail("TokenDetails is nil"); done(); return } expect(tokenDetails.clientId).to(beNil()) - expect(tokenDetails.issued!.dateByAddingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires)) + expect(tokenDetails.issued!.addingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires!)) expect(tokenDetails.capability).to(equal(ExpectedTokenParams.capability)) expect(serverTimeRequestCount) == 1 done() @@ -2987,7 +2988,7 @@ class Auth : QuickSpec { fail("TokenDetails is nil"); done(); return } expect(tokenDetails.clientId).to(beNil()) - expect(tokenDetails.issued!.dateByAddingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires)) + expect(tokenDetails.issued!.addingTimeInterval(ExpectedTokenParams.ttl)).to(beCloseTo(tokenDetails.expires!)) expect(tokenDetails.capability).to(equal(ExpectedTokenParams.capability)) expect(serverTimeRequestCount) == 1 done() @@ -3023,7 +3024,7 @@ class Auth : QuickSpec { } expect(tokenDetails.clientId).to(beNil()) // `ttl` when omitted, the default value is applied - expect(issued.dateByAddingTimeInterval(ARTDefault.ttl())).to(equal(expires)) + expect(issued.addingTimeInterval(ARTDefault.ttl())).to(equal(expires)) done() } } @@ -3042,7 +3043,7 @@ class Auth : QuickSpec { fail("TokenDetails.expires is nil"); done(); return } expect(tokenDetails.clientId).to(beNil()) - expect(issued.dateByAddingTimeInterval(ARTDefault.ttl())).to(equal(expires)) + expect(issued.addingTimeInterval(ARTDefault.ttl())).to(equal(expires)) done() } } @@ -3057,12 +3058,12 @@ class Auth : QuickSpec { let options = AblyTests.commonAppSetup() let rest = ARTRest(options: options) - let mockServerDate = NSDate().dateByAddingTimeInterval(120) - rest.auth.testSuite_returnValueFor(NSSelectorFromString("handleServerTime:"), withDate: mockServerDate) + let mockServerDate = NSDate().addingTimeInterval(120) + rest.auth.testSuite_returnValue(for: NSSelectorFromString("handleServerTime:"), with: mockServerDate as Date) let currentDate = NSDate() var serverTimeRequestCount = 0 - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time(_:))) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time(_:))) { serverTimeRequestCount += 1 } defer { hook.remove() } @@ -3078,7 +3079,7 @@ class Auth : QuickSpec { fail("TokenDetails is nil"); done(); return } expect(rest.auth.timeOffset).toNot(equal(0)) - let calculatedServerDate = currentDate.dateByAddingTimeInterval(rest.auth.timeOffset) + let calculatedServerDate = currentDate.addingTimeInterval(rest.auth.timeOffset) expect(calculatedServerDate).to(beCloseTo(mockServerDate, within: 0.5)) expect(serverTimeRequestCount) == 1 done() @@ -3094,7 +3095,7 @@ class Auth : QuickSpec { fail("TokenDetails is nil"); done(); return } expect(rest.auth.timeOffset).toNot(equal(0)) - let calculatedServerDate = currentDate.dateByAddingTimeInterval(rest.auth.timeOffset) + let calculatedServerDate = currentDate.addingTimeInterval(rest.auth.timeOffset) expect(calculatedServerDate).to(beCloseTo(mockServerDate, within: 0.5)) expect(serverTimeRequestCount) == 1 done() @@ -3106,11 +3107,11 @@ class Auth : QuickSpec { let options = AblyTests.commonAppSetup() let rest = ARTRest(options: options) - let mockServerDate = NSDate().dateByAddingTimeInterval(120) - rest.auth.testSuite_returnValueFor(NSSelectorFromString("handleServerTime:"), withDate: mockServerDate) + let mockServerDate = NSDate().addingTimeInterval(120) + rest.auth.testSuite_returnValue(for: NSSelectorFromString("handleServerTime:"), with: mockServerDate as Date) var serverTimeRequestCount = 0 - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time(_:))) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time(_:))) { serverTimeRequestCount += 1 } defer { hook.remove() } @@ -3140,7 +3141,7 @@ class Auth : QuickSpec { let rest = ARTRest(options: options) var serverTimeRequestCount = 0 - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time(_:))) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time(_:))) { serverTimeRequestCount += 1 } defer { hook.remove() } @@ -3152,8 +3153,8 @@ class Auth : QuickSpec { fail("TokenDetails is nil"); done(); return } expect(rest.auth.timeOffset).toNot(beCloseTo(0)) - let calculatedServerDate = NSDate().dateByAddingTimeInterval(rest.auth.timeOffset) - expect(tokenDetails.expires).to(beCloseTo(calculatedServerDate.dateByAddingTimeInterval(ARTDefault.ttl()), within: 1.0)) + let calculatedServerDate = NSDate().addingTimeInterval(rest.auth.timeOffset) + expect(tokenDetails.expires).to(beCloseTo(calculatedServerDate.addingTimeInterval(ARTDefault.ttl()), within: 1.0)) expect(serverTimeRequestCount) == 1 done() } @@ -3185,7 +3186,7 @@ class Auth : QuickSpec { authOptions.key = options.key authOptions.queryTime = false - let fakeOffset: NSTimeInterval = 60 //1 minute + let fakeOffset: TimeInterval = 60 //1 minute rest.auth.setTimeOffset(fakeOffset) waitUntil(timeout: testTimeout) { done in @@ -3195,7 +3196,7 @@ class Auth : QuickSpec { fail("TokenRequest is nil"); done(); return } expect(rest.auth.timeOffset) == fakeOffset - let calculatedServerDate = NSDate().dateByAddingTimeInterval(rest.auth.timeOffset) + let calculatedServerDate = NSDate().addingTimeInterval(rest.auth.timeOffset) expect(tokenRequest.timestamp).to(beCloseTo(calculatedServerDate, within: 0.5)) done() } @@ -3207,12 +3208,12 @@ class Auth : QuickSpec { let rest = ARTRest(options: options) var serverTimeRequestCount = 0 - let hook = rest.testSuite_injectIntoMethodAfter(#selector(rest.time)) { + let hook = rest.testSuite_injectIntoMethod(after: #selector(rest.time)) { serverTimeRequestCount += 1 } defer { hook.remove() } - let fakeOffset: NSTimeInterval = 60 //1 minute + let fakeOffset: TimeInterval = 60 //1 minute rest.auth.setTimeOffset(fakeOffset) let authOptions = ARTAuthOptions() @@ -3235,18 +3236,18 @@ class Auth : QuickSpec { let rest = ARTRest(options: AblyTests.commonAppSetup()) var discardTimeOffsetCallCount = 0 - let hook = rest.auth.testSuite_injectIntoMethodAfter(#selector(rest.auth.discardTimeOffset)) { + let hook = rest.auth.testSuite_injectIntoMethod(after: #selector(rest.auth.discardTimeOffset)) { discardTimeOffsetCallCount += 1 } defer { hook.remove() } // Force notification - NSNotificationCenter.defaultCenter().postNotificationName(UIApplicationSignificantTimeChangeNotification, object: nil) + NotificationCenter.default.post(name: NSNotification.Name.UIApplicationSignificantTimeChange, object: nil) expect(discardTimeOffsetCallCount).toEventually(equal(1), timeout: testTimeout) // Force notification - NSNotificationCenter.defaultCenter().postNotificationName(NSCurrentLocaleDidChangeNotification, object: nil) + NotificationCenter.default.post(name: NSLocale.currentLocaleDidChangeNotification, object: nil) expect(discardTimeOffsetCallCount).toEventually(equal(2), timeout: testTimeout) } @@ -3256,8 +3257,8 @@ class Auth : QuickSpec { // RSA10l it("has an alias method @RestClient#authorise@ and should use @RealtimeClient#authorize@") { let rest = ARTRest(key: "xxxx:xxxx") - expect(rest.auth.respondsToSelector(#selector(ARTAuth.authorise(_:options:callback:)))) == true - expect(rest.auth.respondsToSelector(#selector(ARTAuth.authorize(_:options:callback:)))) == true + expect(rest.auth.responds(to: #selector(ARTAuth.authorise(_:options:callback:)))) == true + expect(rest.auth.responds(to: #selector(ARTAuth.authorize(_:options:callback:)))) == true } } @@ -3266,23 +3267,23 @@ class Auth : QuickSpec { context("timestamp") { it("if explicitly set, should be returned by the getter") { let params = ARTTokenParams() - params.timestamp = NSDate(timeIntervalSince1970: 123) - expect(params.timestamp).to(equal(NSDate(timeIntervalSince1970: 123))) + params.timestamp = NSDate(timeIntervalSince1970: 123) as Date + expect(params.timestamp).to(equal(NSDate(timeIntervalSince1970: 123) as Date)) } it("if explicitly set, the value should stick") { let params = ARTTokenParams() - params.timestamp = NSDate() + params.timestamp = NSDate() as Date waitUntil(timeout: testTimeout) { done in - let now = NSDate().artToIntegerMs() + let now = Double(NSDate().artToIntegerMs()) guard let timestamp = params.timestamp else { fail("timestamp is nil"); done(); return } - let firstParamsTimestamp = timestamp.artToIntegerMs() + let firstParamsTimestamp = Double((timestamp as NSDate).artToIntegerMs()) expect(firstParamsTimestamp).to(beCloseTo(now, within: 1.5)) delay(0.25) { - expect(timestamp.artToIntegerMs()).to(equal(firstParamsTimestamp)) + expect(Double((timestamp as NSDate).artToIntegerMs())).to(equal(firstParamsTimestamp)) done() } } @@ -3301,7 +3302,7 @@ class Auth : QuickSpec { // RTC8 it("should use authorise({force: true}) to reauth with a token with a different set of capabilities") { let options = AblyTests.commonAppSetup() - let initialToken = getTestToken(capability: "{\"restricted\":[\"*\"]}", clientId: "tester") + let initialToken = getTestToken(clientId: "tester", capability: "{\"restricted\":[\"*\"]}") options.token = initialToken let realtime = ARTRealtime(options: options) defer { realtime.dispose(); realtime.close() } @@ -3349,7 +3350,7 @@ class Auth : QuickSpec { defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.on(.Connected) { stateChange in + realtime.connection.on(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -3368,13 +3369,13 @@ class Auth : QuickSpec { guard let error = error else { fail("Error is nil"); done(); return } - expect(error.code) == 40102 + expect((error as! ARTErrorInfo).code) == 40102 expect(tokenDetails).to(beNil()) done() } } - expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(realtime.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) expect(realtime.auth.tokenDetails?.token).to(equal(initialToken)) expect(realtime.auth.tokenDetails?.capability).toNot(equal(tokenParams.capability)) } @@ -3394,7 +3395,7 @@ class Auth : QuickSpec { expect(defaultTokenParams.timestamp).to(beNil()) var defaultTokenParamsCallCount = 0 - let hook = rest.auth.options.testSuite_injectIntoMethodAfter(NSSelectorFromString("defaultTokenParams")) { + let hook = rest.auth.options.testSuite_injectIntoMethod(after: NSSelectorFromString("defaultTokenParams")) { defaultTokenParamsCallCount += 1 } defer { hook.remove() } @@ -3402,7 +3403,7 @@ class Auth : QuickSpec { let newTokenParams = ARTTokenParams(options: rest.auth.options) expect(defaultTokenParamsCallCount) > 0 - newTokenParams.timestamp = NSDate() + newTokenParams.timestamp = NSDate() as Date expect(newTokenParams.timestamp).toNot(equal(defaultTokenParams.timestamp)) expect(defaultTokenParams.timestamp).to(beNil()) //remain nil done() @@ -3424,32 +3425,32 @@ class Auth : QuickSpec { " \"nonce\":\"7830658976108826\"" + "}" - func check(request: ARTTokenRequest) { + func check(_ request: ARTTokenRequest) { expect(request.clientId).to(equal("myClientId")) expect(request.mac).to(equal("4rr4J+JzjiCL1DoS8wq7k11Z4oTGCb1PoeN+yGjkaH4=")) expect(request.capability).to(equal("{\"test\":[\"publish\"]}")) - expect(request.ttl).to(equal(NSTimeInterval(42))) - expect(request.timestamp).to(equal(NSDate(timeIntervalSince1970: 1479087321.934))) + expect(request.ttl).to(equal(TimeInterval(42))) + expect(request.timestamp).to(equal(NSDate(timeIntervalSince1970: 1479087321.934) as Date)) expect(request.keyName).to(equal("xxxxxx.yyyyyy")) expect(request.nonce).to(equal("7830658976108826")) } it("accepts a string, which should be interpreted as JSON") { - check(try! ARTTokenRequest.fromJson(json)) + check(try! ARTTokenRequest.fromJson(json as ARTJsonCompatible)) } it("accepts a NSDictionary") { - let data = json.dataUsingEncoding(NSUTF8StringEncoding)! - let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! NSDictionary + let data = json.data(using: String.Encoding.utf8)! + let dict = try! JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! NSDictionary check(try! ARTTokenRequest.fromJson(dict)) } it("rejects invalid JSON") { - expect{try ARTTokenRequest.fromJson("not JSON")}.to(throwError()) + expect{try ARTTokenRequest.fromJson("not JSON" as ARTJsonCompatible)}.to(throwError()) } it("rejects non-object JSON") { - expect{try ARTTokenRequest.fromJson("[]")}.to(throwError()) + expect{try ARTTokenRequest.fromJson("[]" as ARTJsonCompatible)}.to(throwError()) } } } @@ -3465,30 +3466,30 @@ class Auth : QuickSpec { " \"clientId\": \"myClientId\"" + "}" - func check(details: ARTTokenDetails) { + func check(_ details: ARTTokenDetails) { expect(details.token).to(equal("xxxxxx.yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")) - expect(details.issued).to(equal(NSDate(timeIntervalSince1970: 1479087321.934))) - expect(details.expires).to(equal(NSDate(timeIntervalSince1970: 1479087363.934))) + expect(details.issued).to(equal(NSDate(timeIntervalSince1970: 1479087321.934) as Date)) + expect(details.expires).to(equal(NSDate(timeIntervalSince1970: 1479087363.934) as Date)) expect(details.capability).to(equal("{\"test\":[\"publish\"]}")) expect(details.clientId).to(equal("myClientId")) } it("accepts a string, which should be interpreted as JSON") { - check(try! ARTTokenDetails.fromJson(json)) + check(try! ARTTokenDetails.fromJson(json as ARTJsonCompatible)) } it("accepts a NSDictionary") { - let data = json.dataUsingEncoding(NSUTF8StringEncoding)! - let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! NSDictionary + let data = json.data(using: String.Encoding.utf8)! + let dict = try! JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! NSDictionary check(try! ARTTokenDetails.fromJson(dict)) } it("rejects invalid JSON") { - expect{try ARTTokenDetails.fromJson("not JSON")}.to(throwError()) + expect{try ARTTokenDetails.fromJson("not JSON" as ARTJsonCompatible)}.to(throwError()) } it("rejects non-object JSON") { - expect{try ARTTokenDetails.fromJson("[]")}.to(throwError()) + expect{try ARTTokenDetails.fromJson("[]" as ARTJsonCompatible)}.to(throwError()) } } } diff --git a/Spec/Crypto.swift b/Spec/Crypto.swift index 1fdea534c..3a38003e4 100644 --- a/Spec/Crypto.swift +++ b/Spec/Crypto.swift @@ -15,9 +15,9 @@ class Crypto : QuickSpec { override func spec() { describe("Crypto") { let key = "+/h4eHh4eHh4eHh4eHh4eA==" - let binaryKey = NSData(base64EncodedString: key, options: NSDataBase64DecodingOptions.init(rawValue: 0))! - var longKey = NSMutableData(data: binaryKey) - longKey.appendData(binaryKey) + let binaryKey = NSData(base64Encoded: key, options: NSData.Base64DecodingOptions.init(rawValue: 0))! + var longKey = NSMutableData(data: binaryKey as Data) + longKey.append(binaryKey as Data) // RSE1 context("getDefaultParams") { @@ -29,7 +29,7 @@ class Crypto : QuickSpec { "key": key ]) expect(params.algorithm).to(equal("AES")) - expect(params.key).to(equal(binaryKey)) + expect(params.key).to(equal(binaryKey as Data)) expect(params.keyLength).to(equal(128)) expect(params.mode).to(equal("CBC")) @@ -38,7 +38,7 @@ class Crypto : QuickSpec { "algorithm": "DES" ]) expect(params.algorithm).to(equal("DES")) - expect(params.key).to(equal(longKey)) + expect(params.key).to(equal(longKey as Data)) expect(params.keyLength).to(equal(256)) expect(params.mode).to(equal("CBC")) } @@ -47,18 +47,18 @@ class Crypto : QuickSpec { context("key parameter") { it("can be a binary") { let params = ARTCrypto.getDefaultParams(["key": binaryKey]) - expect(params.key).to(equal(binaryKey)) + expect(params.key).to(equal(binaryKey as Data)) } it("can be a base64-encoded string with standard encoding") { let params = ARTCrypto.getDefaultParams(["key": key]) - expect(params.key).to(equal(binaryKey)) + expect(params.key).to(equal(binaryKey as Data)) } it("can be a base64-encoded string with URL encoding") { let key = "-_h4eHh4eHh4eHh4eHh4eA==" let params = ARTCrypto.getDefaultParams(["key": key]) - expect(params.key).to(equal(binaryKey)) + expect(params.key).to(equal(binaryKey as Data)) } } @@ -74,7 +74,7 @@ class Crypto : QuickSpec { // RSE1e it("should check that keyLength is valid for algorithm") { expect{ARTCrypto.getDefaultParams([ - "key": binaryKey.subdataWithRange(NSMakeRange(0, 10)) + "key": binaryKey.subdata(with: NSMakeRange(0, 10)) ])}.to(raiseException()) } @@ -84,25 +84,25 @@ class Crypto : QuickSpec { context("generateRandomKey") { // RSE2a, RSE2b it("takes a single length argument and returns a binary") { - var key: NSData = ARTCrypto.generateRandomKey(128) + var key: NSData = ARTCrypto.generateRandomKey(128) as NSData expect(key.length).to(equal(128 / 8)) - key = ARTCrypto.generateRandomKey(256) + key = ARTCrypto.generateRandomKey(256) as NSData expect(key.length).to(equal(256 / 8)) } // RSE2a, RSE2b it("takes no arguments and returns the default algorithm's default length") { - let key: NSData = ARTCrypto.generateRandomKey() + let key: NSData = ARTCrypto.generateRandomKey() as NSData expect(key.length).to(equal(256 / 8)) } } context("encrypt") { it("should generate a new IV every time it's called, and should be the first block encrypted") { - let params = ARTCipherParams(algorithm: "aes", key: key) - let cipher = ARTCrypto.cipherWithParams(params) - let data = "data".dataUsingEncoding(NSUTF8StringEncoding)! + let params = ARTCipherParams(algorithm: "aes", key: key as ARTCipherKeyCompatible) + let cipher = ARTCrypto.cipher(with: params) + let data = "data".data(using: String.Encoding.utf8)! var distinctOutputs = Set() var output: NSData? @@ -111,10 +111,10 @@ class Crypto : QuickSpec { cipher.encrypt(data, output:&output) distinctOutputs.insert(output!) - let firstBlock = output!.subdataWithRange(NSMakeRange(0, Int((cipher as! ARTCbcCipher).blockLength))) - let paramsWithIV = ARTCipherParams(algorithm: "aes", key: key, iv: firstBlock) + let firstBlock = output!.subdata(with: NSMakeRange(0, Int((cipher as! ARTCbcCipher).blockLength))) + let paramsWithIV = ARTCipherParams(algorithm: "aes", key: key as ARTCipherKeyCompatible, iv: firstBlock) var sameOutput: NSData? - ARTCrypto.cipherWithParams(paramsWithIV).encrypt(data, output:&sameOutput) + ARTCrypto.cipher(with: paramsWithIV).encrypt(data, output:&sameOutput) expect(output!).to(equal(sameOutput!)) } @@ -127,10 +127,10 @@ class Crypto : QuickSpec { context("with fixtures from \(cryptoTest).json") { let (key, iv, items) = AblyTests.loadCryptoTestData(cryptoTest) let decoder = ARTDataEncoder.init(cipherParams: nil, error: nil) - let cipherParams = ARTCipherParams(algorithm: "aes", key: key, iv: iv) + let cipherParams = ARTCipherParams(algorithm: "aes", key: key as ARTCipherKeyCompatible, iv: iv) let encrypter = ARTDataEncoder.init(cipherParams: cipherParams, error: nil) - func extractMessage(fixture: AblyTests.CryptoTestItem.TestMessage) -> ARTMessage { + func extractMessage(_ fixture: AblyTests.CryptoTestItem.TestMessage) -> ARTMessage { let msg = ARTMessage(name: fixture.name, data: fixture.data) msg.encoding = fixture.encoding return msg @@ -142,10 +142,10 @@ class Crypto : QuickSpec { let encryptedFixture = extractMessage(item.encrypted) var error: NSError? - let decoded = fixture.decodeWithEncoder(decoder, error: &error) as! ARTMessage + let decoded = fixture.decode(with: decoder, error: &error) as! ARTMessage expect(error).to(beNil()) - let encrypted = decoded.encodeWithEncoder(encrypter, error: &error) + let encrypted = decoded.encode(with: encrypter, error: &error) expect(error).to(beNil()) expect(encrypted as? ARTMessage).to(equal(encryptedFixture)) @@ -158,10 +158,10 @@ class Crypto : QuickSpec { let encryptedFixture = extractMessage(item.encrypted) var error: NSError? - let decoded = fixture.decodeWithEncoder(decoder, error: &error) as! ARTMessage + let decoded = fixture.decode(with: decoder, error: &error) as! ARTMessage expect(error).to(beNil()) - let decrypted = encryptedFixture.decodeWithEncoder(encrypter, error: &error) + let decrypted = encryptedFixture.decode(with: encrypter, error: &error) expect(error).to(beNil()) expect(decrypted as? ARTMessage).to(equal(decoded)) @@ -171,4 +171,4 @@ class Crypto : QuickSpec { } } } -} \ No newline at end of file +} diff --git a/Spec/Helpers.swift b/Spec/Helpers.swift index 5c466902d..c4a56fc04 100644 --- a/Spec/Helpers.swift +++ b/Spec/Helpers.swift @@ -37,7 +37,7 @@ let JSONStringToData: String -> NSData? = { } let JSONDataToAny: NSData -> AnyObject? = { - try? NSJSONSerialization.JSONObjectWithData($0, options: .MutableLeaves) + try? NSJSONSerialization.JSONObjectWithData($0, options: .mutableLeaves) } /** diff --git a/Spec/NSObject+TestSuite.swift b/Spec/NSObject+TestSuite.swift index 8fe6babe4..6234078b8 100644 --- a/Spec/NSObject+TestSuite.swift +++ b/Spec/NSObject+TestSuite.swift @@ -11,19 +11,19 @@ import Aspects extension NSObject { /// Inject a block of code to the identified class method. - class func testSuite_injectIntoClassMethod(selector: Selector, code: ()->()) -> AspectToken? { + class func testSuite_injectIntoClassMethod(_ selector: Selector, code: @escaping ()->()) -> AspectToken? { let block: @convention(block) (AspectInfo) -> Void = { _ in code() } - return try? self.aspect_hookSelector(selector, withOptions: .PositionAfter, usingBlock: unsafeBitCast(block, AnyObject.self)) + return try? self.aspect_hook(selector, with: AspectOptions(), usingBlock: unsafeBitCast(block, to: AnyObject.self)) } /// Replace identified class method with a block of code. - class func testSuite_replaceClassMethod(selector: Selector, code: ()->()) -> AspectToken? { + class func testSuite_replaceClassMethod(_ selector: Selector, code: @escaping ()->()) -> AspectToken? { let block: @convention(block) (AspectInfo) -> Void = { _ in code() } - return try? self.aspect_hookSelector(selector, withOptions: .PositionInstead, usingBlock: unsafeBitCast(block, AnyObject.self)) + return try? self.aspect_hook(selector, with: .positionInstead, usingBlock: unsafeBitCast(block, to: AnyObject.self)) } } diff --git a/Spec/ReadmeExamples.swift b/Spec/ReadmeExamples.swift index 78ca4a352..cc3e7a6f4 100644 --- a/Spec/ReadmeExamples.swift +++ b/Spec/ReadmeExamples.swift @@ -34,10 +34,10 @@ class ReadmeExamples : QuickSpec { client.connection.on { stateChange in let stateChange = stateChange! switch stateChange.current { - case .Connected: + case .connected: print("connected!") - case .Failed: - print("failed! \(stateChange.reason)") + case .failed: + print("failed! \(String(describing: stateChange.reason))") default: break } @@ -60,13 +60,13 @@ class ReadmeExamples : QuickSpec { let channel = client.channels.get("test") channel.subscribe { message in - print(message.name) - print(message.data) + print(message.name as Any) + print(message.data as Any) } channel.subscribe("myEvent") { message in - print(message.name) - print(message.data) + print(message.name as Any) + print(message.data as Any) } channel.publish("greeting", data: "Hello World!") @@ -82,8 +82,8 @@ class ReadmeExamples : QuickSpec { channel.history { messagesPage, error in let messagesPage = messagesPage! print(messagesPage.items) - print(messagesPage.items.first) - print((messagesPage.items.first as? ARTMessage)?.data) // payload for the message + print(messagesPage.items.first as Any) + print(messagesPage.items.first?.data as Any) // payload for the message print(messagesPage.items.count) // number of messages in the current page of history messagesPage.next { nextPage, error in // retrieved the next page in nextPage @@ -99,7 +99,7 @@ class ReadmeExamples : QuickSpec { defer { client.close() } client.connection.on { stateChange in - if stateChange!.current == .Connected { + if stateChange!.current == .connected { let channel = client.channels.get("test") channel.presence.enter("john.doe") { errorInfo in @@ -120,10 +120,10 @@ class ReadmeExamples : QuickSpec { channel.presence.history { presencePage, error in let presencePage = presencePage! - if let first = presencePage.items.first as? ARTPresenceMessage { - print(first.action) // Any of .Enter, .Update or .Leave - print(first.clientId) // client ID of member - print(first.data) // optional data payload of member + if let first = presencePage.items.first { + print(first.action) // Any of .enter, .update or .leave + print(first.clientId as Any) // client ID of member + print(first.data as Any) // optional data payload of member presencePage.next { nextPage, error in // retrieved the next page in nextPage } @@ -152,8 +152,8 @@ class ReadmeExamples : QuickSpec { channel.history { messagesPage, error in let messagesPage = messagesPage! - print(messagesPage.items.first) - print((messagesPage.items.first as? ARTMessage)?.data) // payload for the message + print(messagesPage.items.first as Any) + print(messagesPage.items.first?.data as Any) // payload for the message messagesPage.next { nextPage, error in // retrieved the next page in nextPage } @@ -168,8 +168,8 @@ class ReadmeExamples : QuickSpec { channel.presence.get { membersPage, error in let membersPage = membersPage! - print(membersPage.items.first) - print((membersPage.items.first as? ARTPresenceMessage)?.data) // payload for the message + print(membersPage.items.first as Any) + print((membersPage.items.first)?.data as Any) // payload for the message membersPage.next { nextPage, error in // retrieved the next page in nextPage } @@ -184,8 +184,8 @@ class ReadmeExamples : QuickSpec { channel.presence.history { presencePage, error in let presencePage = presencePage! - if let first = presencePage.items.first as? ARTPresenceMessage { - print(first.clientId) // client ID of member + if let first = presencePage.items.first { + print(first.clientId as Any) // client ID of member presencePage.next { nextPage, error in // retrieved the next page in nextPage } @@ -196,7 +196,7 @@ class ReadmeExamples : QuickSpec { it("testGenerateToken") { let client = ARTRest(options: AblyTests.commonAppSetup()) - client.auth.requestToken(nil, withOptions: nil) { tokenDetails, error in + client.auth.requestToken(nil, with: nil) { tokenDetails, error in let tokenDetails = tokenDetails! print(tokenDetails.token) // "xVLyHw.CLchevH3hF....MDh9ZC_Q" let client = ARTRest(token: tokenDetails.token) @@ -209,7 +209,7 @@ class ReadmeExamples : QuickSpec { client.channels.get("test").publish("foo", data: "bar") { _ in client.stats { statsPage, error in let statsPage = statsPage! - print(statsPage.items.first) + print(statsPage.items.first as Any) statsPage.next { nextPage, error in // retrieved the next page in nextPage } @@ -221,7 +221,7 @@ class ReadmeExamples : QuickSpec { let client = ARTRest(options: AblyTests.commonAppSetup()) client.time { time, error in - print(time) // 2016-02-09 03:59:24 +0000 + print(time as Any) // 2016-02-09 03:59:24 +0000 } } diff --git a/Spec/RealtimeClient.swift b/Spec/RealtimeClient.swift index 922860618..c7c9ac038 100644 --- a/Spec/RealtimeClient.swift +++ b/Spec/RealtimeClient.swift @@ -12,16 +12,16 @@ import Nimble class RealtimeClient: QuickSpec { - func checkError(errorInfo: ARTErrorInfo?, withAlternative message: String) { + func checkError(_ errorInfo: ARTErrorInfo?, withAlternative message: String) { if let error = errorInfo { - XCTFail("\(error.code): \(error.message)") + XCTFail("\((error ).code): \(error.message)") } else if !message.isEmpty { XCTFail(message) } } - func checkError(errorInfo: ARTErrorInfo?) { + func checkError(_ errorInfo: ARTErrorInfo?) { checkError(errorInfo, withAlternative: "") } @@ -57,13 +57,13 @@ class RealtimeClient: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connecting, .Closing, .Closed: + case .connecting, .closing, .closed: break - case .Failed: + case .failed: self.checkError(errorInfo, withAlternative: "Failed state") done() default: - expect(state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(state).to(equal(ARTRealtimeConnectionState.connected)) done() break } @@ -98,10 +98,10 @@ class RealtimeClient: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: self.checkError(errorInfo, withAlternative: "Failed state") done() - case .Connected: + case .connected: self.checkError(errorInfo) expect(client.connection.recoveryKey).to(equal("\(client.connection.key ?? ""):\(client.connection.serial)"), description: "recoveryKey wrong formed") options.recover = client.connection.recoveryKey @@ -122,10 +122,10 @@ class RealtimeClient: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: self.checkError(errorInfo, withAlternative: "Failed state") done() - case .Connected: + case .connected: self.checkError(errorInfo) done() default: @@ -145,7 +145,7 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout * 2) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Connecting) { _ in + client.connection.once(.connecting) { _ in guard let webSocketTransport = client.transport as? ARTWebSocketTransport else { fail("Transport should be of type ARTWebSocketTransport"); done() return @@ -154,11 +154,11 @@ class RealtimeClient: QuickSpec { expect(webSocketTransport.websocketURL?.host).to(equal("fake.ably.io")) partialDone() } - client.connection.once(.Failed) { stateChange in + client.connection.once(.failed) { stateChange in guard let reason = stateChange?.reason else { fail("Reason is nil"); done(); return } - expect(reason.code) == Int(CFNetworkErrors.CFHostErrorUnknown.rawValue) + expect(reason.code) == Int(CFNetworkErrors.cfHostErrorUnknown.rawValue) expect(reason.message).to(contain("kCFErrorDomainCFNetwork")) partialDone() } @@ -189,7 +189,7 @@ class RealtimeClient: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - expect(client.connection).to(beAKindOf(ARTConnection)) + expect(client.connection).to(beAKindOf(ARTConnection.self)) } // RTC3 @@ -229,10 +229,10 @@ class RealtimeClient: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: self.checkError(errorInfo, withAlternative: "Failed state") done() - case .Connected: + case .connected: self.checkError(errorInfo) expect(client.auth.clientId).to(equal(options.clientId)) done() @@ -246,7 +246,7 @@ class RealtimeClient: QuickSpec { context("stats") { let query = ARTStatsQuery() - query.unit = .Minute + query.unit = .minute // RTC5a it("should present an async interface") { @@ -266,14 +266,14 @@ class RealtimeClient: QuickSpec { it("should accept all the same params as RestClient") { let client = ARTRealtime(options: AblyTests.commonAppSetup()) defer { client.close() } - var paginatedResult: ARTPaginatedResult? + var paginatedResult: ARTPaginatedResult? // Realtime try! client.stats(query, callback: { paginated, error in if let e = error { - XCTFail(e.description) + XCTFail(e.localizedDescription) } - paginatedResult = paginated + paginatedResult = paginated as! ARTPaginatedResult? }) expect(paginatedResult).toEventuallyNot(beNil(), timeout: testTimeout) if paginatedResult == nil { @@ -285,7 +285,7 @@ class RealtimeClient: QuickSpec { try! client.rest.stats(query, callback: { paginated, error in defer { done() } if let e = error { - XCTFail(e.description) + XCTFail(e.localizedDescription) return } guard let paginated = paginated else { @@ -331,15 +331,15 @@ class RealtimeClient: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: self.checkError(errorInfo, withAlternative: "Failed state") done() - case .Connecting: + case .connecting: if let start = start { endInterval = UInt(start.timeIntervalSinceNow * -1) done() } - case .Connected: + case .connected: self.checkError(errorInfo) if start == nil { @@ -348,7 +348,7 @@ class RealtimeClient: QuickSpec { client.onSuspended() } } - case .Suspended: + case .suspended: start = NSDate() default: break @@ -371,10 +371,10 @@ class RealtimeClient: QuickSpec { options.useTokenAuth = true let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -396,7 +396,7 @@ class RealtimeClient: QuickSpec { fail("TokenDetails is nil"); done(); return } - let authMessages = transport.protocolMessagesSent.filter({ $0.action == .Auth }) + let authMessages = transport.protocolMessagesSent.filter({ $0.action == .auth }) expect(authMessages).to(haveCount(1)) guard let authMessage = authMessages.first else { @@ -425,10 +425,10 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -438,24 +438,24 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in fail("Should not receive a CONNECTED event because the connection is already connected"); partialDone(); return } - client.connection.once(.Update) { stateChange in + client.connection.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connected)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connected)) expect(stateChange.reason).to(beNil()) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); partialDone(); return } - let connectedMessages = transport.protocolMessagesReceived.filter{ $0.action == .Connected } + let connectedMessages = transport.protocolMessagesReceived.filter{ $0.action == .connected } expect(connectedMessages).to(haveCount(2)) - guard let connectedAfterAuth = connectedMessages.last, connectionDetailsAfterAuth = connectedAfterAuth.connectionDetails else { + guard let connectedAfterAuth = connectedMessages.last, let connectionDetailsAfterAuth = connectedAfterAuth.connectionDetails else { fail("Missing CONNECTED protocol message after AUTH protocol message"); partialDone(); return } @@ -488,10 +488,10 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -500,7 +500,7 @@ class RealtimeClient: QuickSpec { let channel = client.channels.get("foo") waitUntil(timeout: testTimeout) { done in - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("Error is nil"); done(); return } @@ -513,25 +513,25 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Update) { stateChange in + client.connection.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connected)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connected)) expect(stateChange.reason).to(beNil()) partialDone() } - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in fail("Already connected") } - client.connection.once(.Disconnected) { _ in + client.connection.once(.disconnected) { _ in fail("Lost connectivity") } - client.connection.once(.Suspended) { _ in + client.connection.once(.suspended) { _ in fail("Lost continuity") } - client.connection.once(.Failed) { _ in + client.connection.once(.failed) { _ in fail("Should not receive any failure") } @@ -555,16 +555,16 @@ class RealtimeClient: QuickSpec { fail("TestProxyTransport is not set"); return } - expect(transport.protocolMessagesReceived.filter{ $0.action == .Disconnected }).to(beEmpty()) + expect(transport.protocolMessagesReceived.filter{ $0.action == .disconnected }).to(beEmpty()) // Should have one error: Channel denied access - expect(transport.protocolMessagesReceived.filter{ $0.action == .Error }).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter{ $0.action == .error }).to(haveCount(1)) // Retry Channel attach waitUntil(timeout: testTimeout) { done in - channel.once(.Failed) { _ in + channel.once(.failed) { _ in fail("Should not reach Failed state"); done(); return } - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -582,7 +582,7 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) let channel = client.channels.get("foo") waitUntil(timeout: testTimeout) { done in @@ -596,25 +596,25 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("ErrorInfo is nil"); partialDone(); return } expect(error).to(beIdenticalTo(channel.errorReason)) - expect(error.code).to(equal(40160)) + expect((error ).code).to(equal(40160)) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); partialDone(); return } - let errorMessages = transport.protocolMessagesReceived.filter{ $0.action == .Error } + let errorMessages = transport.protocolMessagesReceived.filter{ $0.action == .error } expect(errorMessages).to(haveCount(1)) guard let errorMessage = errorMessages.first else { fail("Missing ERROR protocol message"); partialDone(); return } expect(errorMessage.channel).to(contain("test")) - expect(errorMessage.error?.code).to(equal(error.code)) + expect(errorMessage.error?.code).to(equal((error ).code)) partialDone() } @@ -643,10 +643,10 @@ class RealtimeClient: QuickSpec { options.useTokenAuth = true let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -659,11 +659,11 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Failed) { stateChange in + client.connection.once(.failed) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connected)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connected)) expect(stateChange.reason).toNot(beNil()) connectionError = stateChange.reason partialDone() @@ -672,16 +672,16 @@ class RealtimeClient: QuickSpec { let authOptions = ARTAuthOptions() authOptions.authCallback = { tokenParams, completion in let invalidToken = "xxxxxxxxxxxx" - completion(invalidToken, nil) + completion(invalidToken as ARTTokenDetailsCompatible?, nil) } client.auth.authorize(nil, options: authOptions) { tokenDetails, error in guard let error = error else { fail("ErrorInfo is nil"); partialDone(); return } - expect(error.description).to(contain("Invalid accessToken")) + expect(error.localizedDescription).to(contain("Invalid accessToken")) expect(tokenDetails).to(beNil()) - authError = error + authError = error as NSError? partialDone() } } @@ -696,10 +696,10 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -716,17 +716,17 @@ class RealtimeClient: QuickSpec { } client.auth.authorize(tokenParams, options: authOptions) { tokenDetails, error in - guard let error = error else { + guard let error = error as? ARTErrorInfo else { fail("ErrorInfo is nil"); done(); return } - expect(error.code).to(equal(40102)) - expect(error.description).to(contain("incompatible credentials")) + expect((error ).code).to(equal(40102)) + expect(error.localizedDescription).to(contain("incompatible credentials")) expect(tokenDetails).to(beNil()) done() } } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(client.auth.tokenDetails!.token).to(equal(testToken)) } @@ -737,10 +737,10 @@ class RealtimeClient: QuickSpec { options.useTokenAuth = true let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -756,9 +756,9 @@ class RealtimeClient: QuickSpec { fail("TestProxyTransport is not set"); done(); return } - expect(transport.protocolMessagesSent.filter({ $0.action == .Auth })).to(haveCount(1)) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Connected })).to(haveCount(2)) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Error })).to(haveCount(0)) + expect(transport.protocolMessagesSent.filter({ $0.action == .auth })).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .connected })).to(haveCount(2)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .error })).to(haveCount(0)) done() } } @@ -771,10 +771,10 @@ class RealtimeClient: QuickSpec { options.useTokenAuth = true let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) var connections = 0 - let hook1 = TestProxyTransport.testSuite_injectIntoClassMethod(#selector(TestProxyTransport.connectWithToken(_:))) { + let hook1 = TestProxyTransport.testSuite_injectIntoClassMethod(#selector(TestProxyTransport.connect(withToken:))) { connections += 1 } defer { hook1?.remove() } @@ -786,7 +786,7 @@ class RealtimeClient: QuickSpec { defer { hook2?.remove() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in expect(stateChange?.reason).to(beNil()) let authOptions = ARTAuthOptions() @@ -798,12 +798,12 @@ class RealtimeClient: QuickSpec { fail("TokenDetails is nil"); done(); return } expect(tokenDetails.token).toNot(beNil()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); done(); return } - expect(transport.protocolMessagesReceived.filter({ $0.action == .Connected })).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .connected })).to(haveCount(1)) done() } } @@ -813,7 +813,7 @@ class RealtimeClient: QuickSpec { expect(connections) == 2 expect(connectionsOpened) == 1 - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) } // RTC8b1 - part 1 @@ -824,7 +824,7 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in let authOptions = ARTAuthOptions() @@ -840,7 +840,7 @@ class RealtimeClient: QuickSpec { } } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) } // RTC8b1 - part 2 @@ -850,17 +850,17 @@ class RealtimeClient: QuickSpec { options.useTokenAuth = true let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } client.connect() } - let hook = client.auth.testSuite_injectIntoMethodAfter(#selector(client.auth.authorize(_:options:callback:))) { + let hook = client.auth.testSuite_injectIntoMethod(after: #selector(client.auth.authorize(_:options:callback:))) { guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } @@ -871,7 +871,7 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Failed) { stateChange in + client.connection.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("ErrorInfo is nil"); partialDone(); return } @@ -883,13 +883,13 @@ class RealtimeClient: QuickSpec { guard let error = error else { fail("ErrorInfo is nil"); partialDone(); return } - expect(error.description).to(contain("Fail test")) + expect(error.localizedDescription).to(contain("Fail test")) expect(tokenDetails).to(beNil()) partialDone() } } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.failed)) } // RTC8b1 - part 3 @@ -899,17 +899,17 @@ class RealtimeClient: QuickSpec { options.useTokenAuth = true let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } client.connect() } - let hook = client.auth.testSuite_injectIntoMethodAfter(#selector(client.auth.authorize(_:options:callback:))) { + let hook = client.auth.testSuite_injectIntoMethod(after: #selector(client.auth.authorize(_:options:callback:))) { client.onSuspended() } defer { hook.remove() } @@ -917,7 +917,7 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Suspended) { _ in + client.connection.once(.suspended) { _ in partialDone() } @@ -925,13 +925,13 @@ class RealtimeClient: QuickSpec { guard let error = error else { fail("ErrorInfo is nil"); partialDone(); return } - expect(UInt(error.code)) == ARTState.AuthorizationFailed.rawValue + expect(UInt((error as! ARTErrorInfo).code)) == ARTState.authorizationFailed.rawValue expect(tokenDetails).to(beNil()) partialDone() } } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Suspended)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.suspended)) } // RTC8b1 - part 4 @@ -941,17 +941,17 @@ class RealtimeClient: QuickSpec { options.useTokenAuth = true let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } client.connect() } - let hook = client.auth.testSuite_injectIntoMethodAfter(#selector(client.auth.authorize(_:options:callback:))) { + let hook = client.auth.testSuite_injectIntoMethod(after: #selector(client.auth.authorize(_:options:callback:))) { delay(0) { client.close() } @@ -961,7 +961,7 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Closed) { _ in + client.connection.once(.closed) { _ in partialDone() } @@ -969,13 +969,13 @@ class RealtimeClient: QuickSpec { guard let error = error else { fail("ErrorInfo is nil"); partialDone(); return } - expect(UInt(error.code)) == ARTState.AuthorizationFailed.rawValue + expect(UInt((error as! ARTErrorInfo).code)) == ARTState.authorizationFailed.rawValue expect(tokenDetails).to(beNil()) partialDone() } } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closed)) } // RTC8c - part 1 @@ -986,10 +986,10 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -997,25 +997,25 @@ class RealtimeClient: QuickSpec { } client.onSuspended() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Suspended), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.suspended), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Suspended)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.suspended)) expect(stateChange.reason).to(beNil()) partialDone() } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) expect(stateChange.reason).to(beNil()) partialDone() } @@ -1026,14 +1026,14 @@ class RealtimeClient: QuickSpec { fail("TokenDetails is nil"); partialDone(); return } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(tokenDetails.token).toNot(equal(testToken)) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); partialDone(); return } - expect(transport.protocolMessagesSent.filter({ $0.action == .Auth })).to(haveCount(0)) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Connected })).to(haveCount(1)) //New transport + expect(transport.protocolMessagesSent.filter({ $0.action == .auth })).to(haveCount(0)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .connected })).to(haveCount(1)) //New transport partialDone() } } @@ -1047,10 +1047,10 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -1058,25 +1058,25 @@ class RealtimeClient: QuickSpec { } client.close() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Closed), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.closed), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Closed)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.closed)) expect(stateChange.reason).to(beNil()) partialDone() } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) expect(stateChange.reason).to(beNil()) partialDone() } @@ -1087,14 +1087,14 @@ class RealtimeClient: QuickSpec { fail("TokenDetails is nil"); partialDone(); return } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(tokenDetails.token).toNot(equal(testToken)) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); partialDone(); return } - expect(transport.protocolMessagesSent.filter({ $0.action == .Auth })).to(haveCount(0)) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Connected })).to(haveCount(1)) //New transport + expect(transport.protocolMessagesSent.filter({ $0.action == .auth })).to(haveCount(0)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .connected })).to(haveCount(1)) //New transport partialDone() } } @@ -1108,10 +1108,10 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -1119,25 +1119,25 @@ class RealtimeClient: QuickSpec { } client.onDisconnected() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Disconnected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.disconnected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Disconnected)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.disconnected)) expect(stateChange.reason).to(beNil()) partialDone() } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) expect(stateChange.reason).to(beNil()) partialDone() } @@ -1148,14 +1148,14 @@ class RealtimeClient: QuickSpec { fail("TokenDetails is nil"); partialDone(); return } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(tokenDetails.token).toNot(equal(testToken)) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); partialDone(); return } - expect(transport.protocolMessagesSent.filter({ $0.action == .Auth })).to(haveCount(0)) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Connected })).to(haveCount(1)) //New transport + expect(transport.protocolMessagesSent.filter({ $0.action == .auth })).to(haveCount(0)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .connected })).to(haveCount(1)) //New transport partialDone() } } @@ -1169,10 +1169,10 @@ class RealtimeClient: QuickSpec { options.token = testToken let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -1180,25 +1180,25 @@ class RealtimeClient: QuickSpec { } client.onError(AblyTests.newErrorProtocolMessage()) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Failed), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.failed), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Failed)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.failed)) expect(stateChange.reason).to(beNil()) partialDone() } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); partialDone(); return } - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) expect(stateChange.reason).to(beNil()) partialDone() } @@ -1209,14 +1209,14 @@ class RealtimeClient: QuickSpec { fail("TokenDetails is nil"); partialDone(); return } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(tokenDetails.token).toNot(equal(testToken)) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); partialDone(); return } - expect(transport.protocolMessagesSent.filter({ $0.action == .Auth })).to(haveCount(0)) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Connected })).to(haveCount(1)) //New transport + expect(transport.protocolMessagesSent.filter({ $0.action == .auth })).to(haveCount(0)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .connected })).to(haveCount(1)) //New transport partialDone() } } @@ -1226,7 +1226,7 @@ class RealtimeClient: QuickSpec { // https://github.com/ably/ably-ios/issues/577 it("background behaviour") { waitUntil(timeout: testTimeout) { done in - NSURLSession.sharedSession().dataTaskWithURL(NSURL(string:"https://ably.io")!) { _ in + URLSession.shared.dataTask(with: NSURL(string:"https://ably.io")! as URL) { _ in let realtime = ARTRealtime(options: AblyTests.commonAppSetup()) realtime.channels.get("foo").attach { error in expect(error).to(beNil()) @@ -1253,8 +1253,8 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in transport.beforeProcessingReceivedMessage = { pm in - if pm.action == .Ack, let msgSerial = pm.msgSerial { - switch msgSerial.integerValue { + if pm.action == .ack, let msgSerial = pm.msgSerial { + switch msgSerial.intValue { case 0: pm.msgSerial = 3 case 1: @@ -1291,7 +1291,7 @@ class RealtimeClient: QuickSpec { let realtime = ARTRealtime(options: AblyTests.commonAppSetup()) defer { realtime.dispose(); realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.on(.Connected) { _ in + realtime.connection.on(.connected) { _ in done() } } @@ -1305,8 +1305,8 @@ class RealtimeClient: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(expectedOrder.count, done: done) - realtime.testSuite_getArgumentFrom(NSSelectorFromString("ack:"), atIndex: 0) { object in - guard let value = (object as? ARTProtocolMessage)?.msgSerial?.integerValue else { + realtime.testSuite_getArgument(from: NSSelectorFromString("ack:"), at: 0) { object in + guard let value = (object as? ARTProtocolMessage)?.msgSerial?.intValue else { return } result.append(value) @@ -1315,8 +1315,8 @@ class RealtimeClient: QuickSpec { for i in expectedOrder { let message = ARTProtocolMessage() - message.action = .Ack - message.msgSerial = i + message.action = .ack + message.msgSerial = i as NSNumber webSocketTransport.webSocket(webSocketTransport.websocket!, didReceiveMessage: message) } } @@ -1332,14 +1332,14 @@ class RealtimeClient: QuickSpec { client.connect() client.close() // Before it connects; this registers a listener on the internal event emitter. - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connecting)) client.connection.off() // If we didn't have a separate internal event emitter, the line above would unregister // the listener, and the next lines would fail, because we would never move to // CLOSED, because we do that on the internal event listener registered when // we called close(). - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connecting)) // Still connecting... - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Closed), timeout: testTimeout) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connecting)) // Still connecting... + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.closed), timeout: testTimeout) } it("should never register any message and channel listeners for internal use with the public EventEmitter") { @@ -1353,12 +1353,12 @@ class RealtimeClient: QuickSpec { done() } } - if channel.state != .Attached { + if channel.state != .attached { return } client.onDisconnected() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Disconnected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.disconnected)) // If we now send a message through the channel, it will be queued and the channel // should register a listener in the connection's _internal_ event emitter. diff --git a/Spec/RealtimeClientChannel.swift b/Spec/RealtimeClientChannel.swift index 28e541f49..65a6b1be3 100644 --- a/Spec/RealtimeClientChannel.swift +++ b/Spec/RealtimeClientChannel.swift @@ -40,14 +40,14 @@ class RealtimeClientChannel: QuickSpec { channel2.attach() - expect(channel2.presence.syncComplete).to(beFalse()) + expect(channel2.presence.getSyncComplete).to(beFalse()) expect(channel1.presenceMap.members).to(haveCount(1)) expect(channel2.presenceMap.members).to(haveCount(0)) - expect(channel2.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel2.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) - expect(channel2.presence.syncComplete).toEventually(beTrue(), timeout: testTimeout) + expect(channel2.presence.getSyncComplete).toEventually(beTrue(), timeout: testTimeout) expect(channel1.presenceMap.members).to(haveCount(1)) expect(channel2.presenceMap.members).toEventually(haveCount(1), timeout: testTimeout) @@ -65,15 +65,15 @@ class RealtimeClientChannel: QuickSpec { done() } } - + expect(channel1.presenceMap.members).toEventually(haveCount(2), timeout: testTimeout) - expect(channel1.presenceMap.members).to(allKeysPass({ $0.hasPrefix("Client") })) - expect(channel1.presenceMap.members).to(allValuesPass({ $0.action == .Present })) + expect(channel1.presenceMap.members.keys).to(allPass({ $0!.hasPrefix("Client") })) + expect(channel1.presenceMap.members.values).to(allPass({ $0!.action == .present })) expect(channel2.presenceMap.members).toEventually(haveCount(2), timeout: testTimeout) - expect(channel2.presenceMap.members).to(allKeysPass({ $0.hasPrefix("Client") })) - expect(channel2.presenceMap.members["Client 1"]!.action).to(equal(ARTPresenceAction.Present)) - expect(channel2.presenceMap.members["Client 2"]!.action).to(equal(ARTPresenceAction.Present)) + expect(channel2.presenceMap.members.keys).to(allPass({ $0!.hasPrefix("Client") })) + expect(channel2.presenceMap.members["Client 1"]!.action).to(equal(ARTPresenceAction.present)) + expect(channel2.presenceMap.members["Client 2"]!.action).to(equal(ARTPresenceAction.present)) } // RTL2 @@ -85,21 +85,21 @@ class RealtimeClientChannel: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(channel.statesEventEmitter).to(beAKindOf(ARTEventEmitter.self)) + expect(channel.statesEventEmitter).to(beAKindOf(ARTEventEmitter.self)) var channelOnMethodCalled = false - channel.testSuite_injectIntoMethodAfter(#selector(ARTEventEmitter.on(_:))) { + channel.testSuite_injectIntoMethod(after: #selector(ARTEventEmitter.on(_:))) { channelOnMethodCalled = true } // The `channel.on` should use `statesEventEmitter` var statesEventEmitterOnMethodCalled = false - channel.statesEventEmitter.testSuite_injectIntoMethodAfter(#selector(ARTEventEmitter.on(_:))) { + channel.statesEventEmitter.testSuite_injectIntoMethod(after: #selector(ARTEventEmitter.on(_:))) { statesEventEmitterOnMethodCalled = true } var emitCounter = 0 - channel.statesEventEmitter.testSuite_injectIntoMethodAfter(#selector(ARTEventEmitter.emit(_:with:))) { + channel.statesEventEmitter.testSuite_injectIntoMethod(after: #selector(ARTEventEmitter.emit(_:with:))) { emitCounter += 1 } @@ -114,12 +114,12 @@ class RealtimeClientChannel: QuickSpec { states += [stateChange.current] switch stateChange.current { - case .Attached: - expect(stateChange.event).to(equal(ARTChannelEvent.Attached)) + case .attached: + expect(stateChange.event).to(equal(ARTChannelEvent.attached)) expect(stateChange.reason).to(beNil()) channel.detach() - case .Detached: - expect(stateChange.event).to(equal(ARTChannelEvent.Detached)) + case .detached: + expect(stateChange.event).to(equal(ARTChannelEvent.detached)) guard let error = stateChange.reason else { fail("Detach state change reason is nil"); done(); return } @@ -141,11 +141,11 @@ class RealtimeClientChannel: QuickSpec { return } - expect(states[0].rawValue).to(equal(ARTRealtimeChannelState.Initialized.rawValue), description: "Should be INITIALIZED state") - expect(states[1].rawValue).to(equal(ARTRealtimeChannelState.Attaching.rawValue), description: "Should be ATTACHING state") - expect(states[2].rawValue).to(equal(ARTRealtimeChannelState.Attached.rawValue), description: "Should be ATTACHED state") - expect(states[3].rawValue).to(equal(ARTRealtimeChannelState.Detaching.rawValue), description: "Should be DETACHING state") - expect(states[4].rawValue).to(equal(ARTRealtimeChannelState.Detached.rawValue), description: "Should be DETACHED state") + expect(states[0].rawValue).to(equal(ARTRealtimeChannelState.initialized.rawValue), description: "Should be INITIALIZED state") + expect(states[1].rawValue).to(equal(ARTRealtimeChannelState.attaching.rawValue), description: "Should be ATTACHING state") + expect(states[2].rawValue).to(equal(ARTRealtimeChannelState.attached.rawValue), description: "Should be ATTACHED state") + expect(states[3].rawValue).to(equal(ARTRealtimeChannelState.detaching.rawValue), description: "Should be DETACHING state") + expect(states[4].rawValue).to(equal(ARTRealtimeChannelState.detached.rawValue), description: "Should be DETACHED state") } // RTL2a @@ -163,17 +163,17 @@ class RealtimeClientChannel: QuickSpec { } expect(channel.state).to(equal(stateChange.current)) switch stateChange.current { - case .Attaching: - expect(stateChange.event).to(equal(ARTChannelEvent.Attaching)) + case .attaching: + expect(stateChange.event).to(equal(ARTChannelEvent.attaching)) expect(stateChange.reason).to(beNil()) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Initialized)) - case .Failed: + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.initialized)) + case .failed: guard let reason = stateChange.reason else { fail("Reason is nil"); done(); return } - expect(stateChange.event).to(equal(ARTChannelEvent.Failed)) + expect(stateChange.event).to(equal(ARTChannelEvent.failed)) expect(reason.code) == 40160 - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attaching)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attaching)) done() default: break @@ -197,13 +197,13 @@ class RealtimeClientChannel: QuickSpec { } client.simulateSuspended(beforeSuspension: { done in - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) - expect(stateChange.event).to(equal(ARTChannelEvent.Suspended)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) + expect(stateChange.event).to(equal(ARTChannelEvent.suspended)) expect(channel.state).to(equal(stateChange.current)) done() } @@ -222,7 +222,7 @@ class RealtimeClientChannel: QuickSpec { } } - channel.on(.Attached) { _ in + channel.on(.attached) { _ in fail("Should not emit Attached again") } defer { @@ -230,21 +230,21 @@ class RealtimeClientChannel: QuickSpec { } waitUntil(timeout: testTimeout) { done in - channel.on(.Update) { stateChange in + channel.on(.update) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); done(); return } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) expect(stateChange.previous).to(equal(channel.state)) expect(stateChange.current).to(equal(channel.state)) - expect(stateChange.event).to(equal(ARTChannelEvent.Update)) + expect(stateChange.event).to(equal(ARTChannelEvent.update)) expect(stateChange.resumed).to(beFalse()) expect(stateChange.reason).to(beNil()) done() } let attachedMessage = ARTProtocolMessage() - attachedMessage.action = .Attached + attachedMessage.action = .attached attachedMessage.channel = "foo" client.transport?.receive(attachedMessage) } @@ -256,11 +256,11 @@ class RealtimeClientChannel: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) channel.attach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) } // RTL2c @@ -271,7 +271,7 @@ class RealtimeClientChannel: QuickSpec { let pmError = AblyTests.newErrorProtocolMessage() waitUntil(timeout: testTimeout) { done in - channel.on(.Failed) { stateChange in + channel.on(.failed) { stateChange in guard let error = stateChange?.reason else { fail("Error is nil"); done(); return } @@ -299,17 +299,17 @@ class RealtimeClientChannel: QuickSpec { } channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) channel.off() waitUntil(timeout: testTimeout) { done in - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } expect(stateChange.reason).toNot(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Failed)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.failed)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) done() } channel.onError(AblyTests.newErrorProtocolMessage()) @@ -331,13 +331,13 @@ class RealtimeClientChannel: QuickSpec { fail("ChannelStageChange is nil"); done(); return } switch stateChange.current { - case .Attached: + case .attached: expect(stateChange.resumed).to(beFalse()) default: expect(stateChange.resumed).to(beFalse()) } } - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in channel.off() guard let error = stateChange?.reason else { fail("Error is nil"); done(); return @@ -349,14 +349,14 @@ class RealtimeClientChannel: QuickSpec { } waitUntil(timeout: testTimeout) { done in - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } expect(stateChange.resumed).to(beTrue()) expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) done() } } @@ -370,7 +370,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } @@ -382,19 +382,19 @@ class RealtimeClientChannel: QuickSpec { } let attachedMessage = ARTProtocolMessage() - attachedMessage.action = .Attached + attachedMessage.action = .attached attachedMessage.channel = "test" attachedMessage.flags = 4 //Resumed waitUntil(timeout: testTimeout) { done in - channel.once(.Update) { stateChange in + channel.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } expect(stateChange.resumed).to(beTrue()) expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) done() } client.transport?.receive(attachedMessage) @@ -413,20 +413,20 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") channel.attach() let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Attached] + transport.actionsIgnored += [.attached] - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) waitUntil(timeout: testTimeout) { done in let pmError = AblyTests.newErrorProtocolMessage() - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -437,7 +437,7 @@ class RealtimeClientChannel: QuickSpec { client.onError(pmError) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) } it("ATTACHED channel should transition to FAILED") { @@ -446,11 +446,11 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in let pmError = AblyTests.newErrorProtocolMessage() - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -461,7 +461,7 @@ class RealtimeClientChannel: QuickSpec { client.onError(pmError) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) } } @@ -473,21 +473,21 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let channel = client.channels.get("test") channel.attach() let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Attached] + transport.actionsIgnored += [.attached] - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) client.close() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closing)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closing)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closed)) } it("ATTACHED channel should transition to DETACHED") { @@ -498,11 +498,11 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) client.close() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closing)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closing)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closed)) } } @@ -514,19 +514,19 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") channel.attach() let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Attached] + transport.actionsIgnored += [.attached] - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) client.onSuspended() - expect(channel.state).to(equal(ARTRealtimeChannelState.Suspended)) + expect(channel.state).to(equal(ARTRealtimeChannelState.suspended)) } it("ATTACHED channel should transition to SUSPENDED") { @@ -536,9 +536,9 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) client.onSuspended() - expect(channel.state).to(equal(ARTRealtimeChannelState.Suspended)) + expect(channel.state).to(equal(ARTRealtimeChannelState.suspended)) } } @@ -559,7 +559,7 @@ class RealtimeClientChannel: QuickSpec { } waitUntil(timeout: testTimeout) { done in - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -568,8 +568,8 @@ class RealtimeClientChannel: QuickSpec { } } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) } // RTL3d @@ -586,7 +586,7 @@ class RealtimeClientChannel: QuickSpec { } client.simulateSuspended(beforeSuspension: { done in - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); done(); return } @@ -605,7 +605,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") - channel.once(.Detached) { stateChange in + channel.once(.detached) { stateChange in fail("Should not reach the DETACHED state") } defer { @@ -620,8 +620,8 @@ class RealtimeClientChannel: QuickSpec { } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Disconnected) { _ in - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + client.connection.once(.disconnected) { _ in + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) done() } } @@ -643,19 +643,19 @@ class RealtimeClientChannel: QuickSpec { channel.attach { errorInfo in expect(errorInfo).to(beNil()) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) channel.attach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) } - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.attach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) done() } } @@ -671,7 +671,7 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in expect(stateChange?.reason?.code) == 40160 partialDone() } @@ -679,12 +679,12 @@ class RealtimeClientChannel: QuickSpec { guard let error = error else { fail("Error is nil"); partialDone(); return } - expect(error.code) == 40160 + expect((error ).code) == 40160 partialDone() } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(channel.errorReason?.code) == 40160 } @@ -695,12 +695,12 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) let errorMsg = AblyTests.newErrorProtocolMessage() errorMsg.channel = channel.name client.onError(errorMsg) - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(channel.errorReason).toNot(beNil()) waitUntil(timeout: testTimeout) { done in @@ -710,7 +710,7 @@ class RealtimeClientChannel: QuickSpec { } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) expect(channel.errorReason).to(beNil()) } @@ -721,18 +721,18 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Closed] + transport.actionsIgnored += [.closed] let channel = client.channels.get("test") client.close() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closing)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closing)) waitUntil(timeout: testTimeout) { done in channel.attach { error in @@ -749,7 +749,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") client.close() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Closed), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.closed), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.attach { error in @@ -765,7 +765,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") client.onSuspended() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Suspended)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.suspended)) waitUntil(timeout: testTimeout) { done in channel.attach { error in expect(error).toNot(beNil()) @@ -780,7 +780,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") client.onError(AblyTests.newErrorProtocolMessage()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.failed)) waitUntil(timeout: testTimeout) { done in channel.attach { error in expect(error).toNot(beNil()) @@ -800,10 +800,10 @@ class RealtimeClientChannel: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Initialized)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.initialized)) waitUntil(timeout: testTimeout) { done in channel.attach { error in - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(error).to(beNil()) done() } @@ -822,10 +822,10 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in client.connect() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connecting)) channel.attach { error in - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(error).to(beNil()) done() } @@ -840,14 +840,14 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in client.onDisconnected() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Disconnected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.disconnected)) channel.attach { error in - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(error).to(beNil()) done() } @@ -860,21 +860,21 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let transport = client.transport as! TestProxyTransport let channel = client.channels.get("test") channel.attach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) - expect(transport.protocolMessagesSent.filter({ $0.action == .Attach })).to(haveCount(1)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) + expect(transport.protocolMessagesSent.filter({ $0.action == .attach })).to(haveCount(1)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Attached })).to(haveCount(1)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) + expect(transport.protocolMessagesReceived.filter({ $0.action == .attached })).to(haveCount(1)) } // RTL4e @@ -888,17 +888,17 @@ class RealtimeClientChannel: QuickSpec { channel.attach() waitUntil(timeout: testTimeout) { done in - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } - expect(error.code).to(equal(40160)) + expect((error ).code).to(equal(40160)) done() } } expect(channel.errorReason!.code).to(equal(40160)) - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) } // RTL4f @@ -908,7 +908,7 @@ class RealtimeClientChannel: QuickSpec { let client = AblyTests.newRealtime(options) defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let previousRealtimeRequestTimeout = ARTDefault.realtimeRequestTimeout() defer { ARTDefault.setRealtimeRequestTimeout(previousRealtimeRequestTimeout) } @@ -917,7 +917,7 @@ class RealtimeClientChannel: QuickSpec { guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } - transport.actionsIgnored += [.Attached] + transport.actionsIgnored += [.attached] let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in @@ -927,18 +927,18 @@ class RealtimeClientChannel: QuickSpec { done() } } - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Suspended), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.suspended), timeout: testTimeout) expect(channel.errorReason).toNot(beNil()) transport.actionsIgnored = [] // Automatically re-attached waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in expect(stateChange?.reason).to(beNil()) partialDone() } - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in expect(stateChange?.reason).to(beNil()) partialDone() } @@ -954,7 +954,7 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.attach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) done() } } @@ -968,10 +968,10 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.attach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) channel.attach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) done() } } @@ -984,7 +984,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.attach { errorInfo in @@ -1002,7 +1002,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("foo") var attachedCount = 0 - channel.on(.Attached) { stateChange in + channel.on(.attached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); return } @@ -1012,17 +1012,17 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attaching)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Initialized)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attaching)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.initialized)) channel.attach() partialDone() } - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in expect(stateChange?.reason).to(beNil()) partialDone() } @@ -1047,41 +1047,41 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(4, done: done) - channel.once(.Detaching) { stateChange in + channel.once(.detaching) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Detaching)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.detaching)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) channel.attach() partialDone() } - channel.once(.Detached) { stateChange in + channel.once(.detached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason?.message).to(contain("channel has detached")) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Detached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Detaching)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.detached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.detaching)) partialDone() } - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attaching)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Detached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attaching)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.detached)) partialDone() } - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attaching)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attaching)) partialDone() } channel.detach() @@ -1109,7 +1109,7 @@ class RealtimeClientChannel: QuickSpec { } // Force timeout - transport.actionsIgnored = [.Detached] + transport.actionsIgnored = [.detached] waitUntil(timeout: testTimeout) { done in channel.detach() { error in @@ -1117,7 +1117,7 @@ class RealtimeClientChannel: QuickSpec { fail("Reason error is nil"); return } expect(error.message).to(contain("timed out")) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) done() } } @@ -1134,26 +1134,26 @@ class RealtimeClientChannel: QuickSpec { var errorInfo: ARTErrorInfo? let channel = client.channels.get("test") - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) channel.detach { errorInfo in expect(errorInfo).to(beNil()) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attaching), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attaching), timeout: testTimeout) channel.detach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) } - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.detach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) done() } } @@ -1173,33 +1173,33 @@ class RealtimeClientChannel: QuickSpec { } var detachedCount = 0 - channel.on(.Detached) { _ in + channel.on(.detached) { _ in detachedCount += 1 } var detachingCount = 0 - channel.on(.Detaching) { _ in + channel.on(.detaching) { _ in detachingCount += 1 } waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.once(.Detaching) { stateChange in + channel.once(.detaching) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); done(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Detaching)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.detaching)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) channel.detach() partialDone() } - channel.once(.Detached) { stateChange in + channel.once(.detached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); done(); return } - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Detached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Detaching)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.detached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.detaching)) partialDone() } channel.detach() @@ -1225,32 +1225,32 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attaching)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Initialized)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attaching)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.initialized)) channel.detach() partialDone() } - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attaching)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attaching)) partialDone() } - channel.once(.Detaching) { stateChange in + channel.once(.detaching) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Detaching)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.detaching)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) partialDone() } channel.attach() @@ -1264,7 +1264,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") client.onError(AblyTests.newErrorProtocolMessage()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.failed)) waitUntil(timeout: testTimeout) { done in channel.detach() { errorInfo in @@ -1279,23 +1279,23 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let transport = client.transport as! TestProxyTransport let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) channel.detach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Detaching)) - expect(transport.protocolMessagesSent.filter({ $0.action == .Detach })).to(haveCount(1)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detaching)) + expect(transport.protocolMessagesSent.filter({ $0.action == .detach })).to(haveCount(1)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Detached })).to(haveCount(1)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) + expect(transport.protocolMessagesReceived.filter({ $0.action == .detached })).to(haveCount(1)) } // RTL5e @@ -1306,12 +1306,12 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.detach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) done() } } @@ -1325,14 +1325,14 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.detach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Detaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detaching)) channel.detach { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) done() } } @@ -1346,9 +1346,9 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) channel.detach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.detach { errorInfo in @@ -1363,13 +1363,13 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Detached] + transport.actionsIgnored += [.detached] let previousRealtimeRequestTimeout = ARTDefault.realtimeRequestTimeout() defer { ARTDefault.setRealtimeRequestTimeout(previousRealtimeRequestTimeout) } @@ -1377,7 +1377,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) var callbackCalled = false channel.detach { error in @@ -1389,11 +1389,11 @@ class RealtimeClientChannel: QuickSpec { callbackCalled = true } let start = NSDate() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) expect(channel.errorReason).toNot(beNil()) expect(callbackCalled).to(beTrue()) let end = NSDate() - expect(start.dateByAddingTimeInterval(1.0)).to(beCloseTo(end, within: 0.5)) + expect(start.addingTimeInterval(1.0)).to(beCloseTo(end, within: 0.5)) } // RTL5g @@ -1403,20 +1403,20 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Closed] + transport.actionsIgnored += [.closed] let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) client.close() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closing)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closing)) waitUntil(timeout: testTimeout) { done in channel.detach { error in @@ -1432,10 +1432,10 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) client.onError(AblyTests.newErrorProtocolMessage()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.failed)) waitUntil(timeout: testTimeout) { done in channel.detach { error in expect(error).toNot(beNil()) @@ -1457,8 +1457,8 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in channel.attach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.initialized)) channel.detach { error in expect(error).to(beNil()) @@ -1480,8 +1480,8 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in client.connect() channel.attach() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connecting)) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connecting)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) channel.detach { error in expect(error).to(beNil()) @@ -1498,16 +1498,16 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in client.onDisconnected() channel.attach() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Disconnected)) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.disconnected)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) channel.detach { error in - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(error).to(beNil()) done() } @@ -1528,18 +1528,18 @@ class RealtimeClientChannel: QuickSpec { } } - channel.setSuspended(ARTStatus.state(.Ok)) - expect(channel.state).to(equal(ARTRealtimeChannelState.Suspended)) + channel.setSuspended(ARTStatus.state(.ok)) + expect(channel.state).to(equal(ARTRealtimeChannelState.suspended)) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.once(.Detached) { stateChange in + channel.once(.detached) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Detached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Suspended)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.detached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.suspended)) partialDone() } channel.detach() { error in @@ -1548,7 +1548,7 @@ class RealtimeClientChannel: QuickSpec { } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) } } @@ -1564,7 +1564,7 @@ class RealtimeClientChannel: QuickSpec { let restChannel = rest.channels.get("test") var restEncodedMessage: ARTMessage? - restChannel.testSuite_getReturnValueFrom(NSSelectorFromString("encodeMessageIfNeeded:error:")) { value in + restChannel.testSuite_getReturnValue(from: NSSelectorFromString("encodeMessageIfNeeded:error:")) { value in restEncodedMessage = value as? ARTMessage } @@ -1579,10 +1579,10 @@ class RealtimeClientChannel: QuickSpec { defer { realtime.close() } let realtimeChannel = realtime.channels.get("test") realtimeChannel.attach() - expect(realtimeChannel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(realtimeChannel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) var realtimeEncodedMessage: ARTMessage? - realtimeChannel.testSuite_getReturnValueFrom(NSSelectorFromString("encodeMessageIfNeeded:error:")) { value in + realtimeChannel.testSuite_getReturnValue(from: NSSelectorFromString("encodeMessageIfNeeded:error:")) { value in realtimeEncodedMessage = value as? ARTMessage } @@ -1613,13 +1613,13 @@ class RealtimeClientChannel: QuickSpec { let stateChange = stateChange! let state = stateChange.current let error = stateChange.reason - if state == .Connected { + if state == .connected { let channel = client.channels.get("test") channel.on { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } - if stateChange.current == .Attached { + if stateChange.current == .attached { channel.publish(nil, data: "message") { errorInfo in expect(errorInfo).to(beNil()) done() @@ -1643,13 +1643,13 @@ class RealtimeClientChannel: QuickSpec { let stateChange = stateChange! let state = stateChange.current let error = stateChange.reason - if state == .Connected { + if state == .connected { let channel = client.channels.get("test") channel.on { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } - if stateChange.current == .Attached { + if stateChange.current == .attached { channel.publish(nil, data: "message") { errorInfo in expect(errorInfo).toNot(beNil()) guard let errorInfo = errorInfo else { @@ -1671,7 +1671,7 @@ class RealtimeClientChannel: QuickSpec { static let expected = 50 static var succeeded = 0 static var failed = 0 - private init() {} + fileprivate init() {} } it("for all messages published") { @@ -1688,7 +1688,7 @@ class RealtimeClientChannel: QuickSpec { guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); return } - if stateChange.current == .Attached { + if stateChange.current == .attached { for index in 1...TotalMessages.expected { channelToSucceed.publish(nil, data: "message\(index)") { errorInfo in if errorInfo == nil { @@ -1706,7 +1706,7 @@ class RealtimeClientChannel: QuickSpec { guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); return } - if stateChange.current == .Attached { + if stateChange.current == .attached { for index in 1...TotalMessages.expected { channelToFail.publish(nil, data: "message\(index)") { errorInfo in if errorInfo != nil { @@ -1735,15 +1735,15 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) waitUntil(timeout: testTimeout) { done in channel.publish(nil, data: "message") { error in expect(error).to(beNil()) done() } - expect((client.transport as! TestProxyTransport).protocolMessagesSent.filter({ $0.action == .Message })).to(haveCount(1)) + expect((client.transport as! TestProxyTransport).protocolMessagesSent.filter({ $0.action == .message })).to(haveCount(1)) } } @@ -1763,17 +1763,17 @@ class RealtimeClientChannel: QuickSpec { } afterEach { client.close() } - func publish(done: () -> ()) { + func publish(_ done: @escaping () -> ()) { channel.publish(nil, data: "message") { error in expect(error).to(beNil()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) done() } } it("INITIALIZED") { waitUntil(timeout: testTimeout) { done in - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Initialized)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.initialized)) publish(done) client.connect() expect(channel.queuedMessages).to(haveCount(1)) @@ -1783,7 +1783,7 @@ class RealtimeClientChannel: QuickSpec { it("CONNECTING") { waitUntil(timeout: testTimeout) { done in client.connect() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connecting)) publish(done) expect(channel.queuedMessages).to(haveCount(1)) } @@ -1791,23 +1791,23 @@ class RealtimeClientChannel: QuickSpec { it("DISCONNECTED") { client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.onDisconnected() waitUntil(timeout: testTimeout) { done in - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Disconnected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.disconnected)) publish(done) expect(channel.queuedMessages).to(haveCount(1)) } } - it("ATTTACHING") { + it("ATTACHING") { client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.attach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) publish(done) expect(channel.queuedMessages).to(haveCount(1)) } @@ -1833,12 +1833,12 @@ class RealtimeClientChannel: QuickSpec { } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Disconnected) { _ in + client.connection.once(.disconnected) { _ in done() } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) waitUntil(timeout: testTimeout) { done in publish(done) @@ -1854,18 +1854,18 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in let protocolError = AblyTests.newErrorProtocolMessage() - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) channel.publish(nil, data: "message") { error in - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(error).to(beIdenticalTo(protocolError.error)) channel.publish(nil, data: "message") { error in - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(error).toNot(beNil()) done() } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) channel.onError(protocolError) } } @@ -1878,8 +1878,8 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) - channel.once(.Attached) { stateChange in + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) + channel.once(.attached) { stateChange in expect(stateChange?.reason).to(beNil()) channel.detach() partialDone() @@ -1889,7 +1889,7 @@ class RealtimeClientChannel: QuickSpec { fail("Error is nil"); done(); return } expect(error.message).to(contain("invalid channel state")) - expect(channel.state).to(equal(ARTRealtimeChannelState.Detaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detaching)) partialDone() } } @@ -1916,7 +1916,7 @@ class RealtimeClientChannel: QuickSpec { ARTDefault.setConnectionStateTtl(previousConnectionStateTtl) } - func publish(done: () -> ()) { + func publish(_ done: @escaping () -> ()) { channel.publish(nil, data: "message") { error in expect(error).toNot(beNil()) done() @@ -1925,9 +1925,9 @@ class RealtimeClientChannel: QuickSpec { it("connection is SUSPENDED") { client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.onSuspended() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Suspended), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.suspended), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -1935,9 +1935,9 @@ class RealtimeClientChannel: QuickSpec { it("connection is CLOSING") { client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.close() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closing)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closing)) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -1945,9 +1945,9 @@ class RealtimeClientChannel: QuickSpec { it("connection is CLOSED") { client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.close() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Closed), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.closed), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -1955,9 +1955,9 @@ class RealtimeClientChannel: QuickSpec { it("connection is FAILED") { client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.onError(AblyTests.newErrorProtocolMessage()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.failed)) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -1966,9 +1966,9 @@ class RealtimeClientChannel: QuickSpec { it("channel is DETACHING") { client.connect() channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) channel.detach() - expect(channel.state).to(equal(ARTRealtimeChannelState.Detaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detaching)) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -1977,9 +1977,9 @@ class RealtimeClientChannel: QuickSpec { it("channel is DETACHED") { client.connect() channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) channel.detach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -1988,9 +1988,9 @@ class RealtimeClientChannel: QuickSpec { it("channel is SUSPENDED") { client.connect() channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) - channel.setSuspended(ARTStatus.state(.Ok)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Suspended), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) + channel.setSuspended(ARTStatus.state(.ok)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.suspended), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -1999,10 +1999,10 @@ class RealtimeClientChannel: QuickSpec { it("channel is FAILED") { client.connect() channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) let protocolError = AblyTests.newErrorProtocolMessage() channel.onError(protocolError) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Failed), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.failed), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in publish(done) } @@ -2033,7 +2033,7 @@ class RealtimeClientChannel: QuickSpec { } let transport = client.transport as! TestProxyTransport - let protocolMessages = transport.protocolMessagesSent.filter{ $0.action == .Message } + let protocolMessages = transport.protocolMessagesSent.filter{ $0.action == .message } expect(protocolMessages).to(haveCount(1)) if protocolMessages.count != 1 { return @@ -2053,7 +2053,7 @@ class RealtimeClientChannel: QuickSpec { channel.publish(messages) { error in expect(error).to(beNil()) let transport = client.transport as! TestProxyTransport - let protocolMessages = transport.protocolMessagesSent.filter{ $0.action == .Message } + let protocolMessages = transport.protocolMessagesSent.filter{ $0.action == .message } expect(protocolMessages).to(haveCount(2)) if protocolMessages.count != 2 { done(); return @@ -2120,7 +2120,7 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") @@ -2136,7 +2136,7 @@ class RealtimeClientChannel: QuickSpec { let transport = client.transport as! TestProxyTransport - expect(transport.protocolMessagesSent.filter{ $0.action == .Message }).toEventually(haveCount(1), timeout: testTimeout) + expect(transport.protocolMessagesSent.filter{ $0.action == .message }).toEventually(haveCount(1), timeout: testTimeout) expect(result).toEventually(equal(messages.map{ $0.data as! JSONObject }), timeout: testTimeout) } @@ -2161,12 +2161,12 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedObject = ["data": "message", "connectionId": client.connection.id!] var resultMessage: ARTMessage? @@ -2182,10 +2182,11 @@ class RealtimeClientChannel: QuickSpec { } let transport = client.transport as! TestProxyTransport - - let rawMessagesSent = transport.rawDataSent.toMsgPackArray.filter({ $0["action"] == ARTProtocolMessageAction.Message.rawValue }) - let messagesList = (rawMessagesSent[0] as! NSDictionary)["messages"] as! NSArray - let resultObject = messagesList[0] as! NSDictionary + + let rawProtoMsgsSent: [NSDictionary] = transport.rawDataSent.toMsgPackArray() + let rawMessagesSent = rawProtoMsgsSent.filter({ $0["action"] as! UInt == ARTProtocolMessageAction.message.rawValue }) + let messagesList = rawMessagesSent[0]["messages"] as! NSArray + let resultObject = messagesList[0] as! [String: String] expect(resultObject).to(equal(expectedObject)) @@ -2198,12 +2199,12 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedObject = ["name": "click", "connectionId": client.connection.id!] var resultMessage: ARTMessage? @@ -2220,11 +2221,12 @@ class RealtimeClientChannel: QuickSpec { let transport = client.transport as! TestProxyTransport - let rawMessagesSent = transport.rawDataSent.toMsgPackArray.filter({ $0["action"] == ARTProtocolMessageAction.Message.rawValue }) - let messagesList = (rawMessagesSent[0] as! NSDictionary)["messages"] as! NSArray + let rawProtoMsgsSent: [NSDictionary] = transport.rawDataSent.toMsgPackArray() + let rawMessagesSent = rawProtoMsgsSent.filter({ $0["action"] as! UInt == ARTProtocolMessageAction.message.rawValue }) + let messagesList = rawMessagesSent[0]["messages"] as! NSArray let resultObject = messagesList[0] as! NSDictionary - expect(resultObject).to(equal(expectedObject)) + expect(resultObject).to(equal(expectedObject as NSDictionary)) expect(resultMessage).toNotEventually(beNil(), timeout: testTimeout) expect(resultMessage!.name).to(equal(expectedObject["name"])) @@ -2235,12 +2237,12 @@ class RealtimeClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedObject = ["name": "click", "data": "message", "connectionId": client.connection.id!] waitUntil(timeout: testTimeout) { done in @@ -2252,11 +2254,12 @@ class RealtimeClientChannel: QuickSpec { let transport = client.transport as! TestProxyTransport - let rawMessagesSent = transport.rawDataSent.toMsgPackArray.filter({ $0["action"] == ARTProtocolMessageAction.Message.rawValue }) - let messagesList = (rawMessagesSent[0] as! NSDictionary)["messages"] as! NSArray + let rawProtoMsgsSent: [NSDictionary] = transport.rawDataSent.toMsgPackArray() + let rawMessagesSent = rawProtoMsgsSent.filter({ $0["action"] as! UInt == ARTProtocolMessageAction.message.rawValue }) + let messagesList = rawMessagesSent[0]["messages"] as! NSArray let resultObject = messagesList[0] as! NSDictionary - expect(resultObject).to(equal(expectedObject)) + expect(resultObject).to(equal(expectedObject as NSDictionary)) } } @@ -2273,7 +2276,7 @@ class RealtimeClientChannel: QuickSpec { options.clientId = "client_string" options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") @@ -2291,10 +2294,10 @@ class RealtimeClientChannel: QuickSpec { let transport = client.transport as! TestProxyTransport - let messageSent = transport.protocolMessagesSent.filter({ $0.action == .Message })[0] + let messageSent = transport.protocolMessagesSent.filter({ $0.action == .message })[0] expect(messageSent.messages![0].clientId).to(beNil()) - let messageReceived = transport.protocolMessagesReceived.filter({ $0.action == .Message })[0] + let messageReceived = transport.protocolMessagesReceived.filter({ $0.action == .message })[0] expect(messageReceived.messages![0].clientId).to(equal(options.clientId)) } @@ -2403,7 +2406,7 @@ class RealtimeClientChannel: QuickSpec { let partialDone = AblyTests.splitDone(2, done: done) channel.subscribe { message in expect(message.name).to(equal("event")) - expect(message.data as? NSObject).to(equal("data")) + expect(message.data as? NSObject).to(equal("data" as NSObject?)) expect(message.clientId).to(equal("foo")) partialDone() } @@ -2429,7 +2432,7 @@ class RealtimeClientChannel: QuickSpec { class Test { static var counter = 0 - private init() {} + fileprivate init() {} } channel.subscribe { message in @@ -2453,7 +2456,7 @@ class RealtimeClientChannel: QuickSpec { class Test { static var counter = 0 - private init() {} + fileprivate init() {} } channel.subscribe("eventA") { message in @@ -2479,11 +2482,11 @@ class RealtimeClientChannel: QuickSpec { let publishedMessage = ARTMessage(name: "foo", data: "bar") waitUntil(timeout: testTimeout) { done in - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) - channel.subscribeWithAttachCallback({ errorInfo in + channel.subscribe(attachCallback: { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) channel.publish([publishedMessage]) }) { message in expect(message.name).to(equal(publishedMessage.name)) @@ -2491,7 +2494,7 @@ class RealtimeClientChannel: QuickSpec { done() } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) } } @@ -2504,7 +2507,7 @@ class RealtimeClientChannel: QuickSpec { channel.subscribe { _ in } - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) } // RTL7c @@ -2514,10 +2517,10 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("test") channel.onError(AblyTests.newErrorProtocolMessage()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) waitUntil(timeout: testTimeout) { done in - channel.subscribeWithAttachCallback({ errorInfo in + channel.subscribe(attachCallback: { errorInfo in expect(errorInfo).toNot(beNil()) channel.subscribe("foo", onAttach: { errorInfo in @@ -2537,29 +2540,29 @@ class RealtimeClientChannel: QuickSpec { options.autoConnect = false options.logHandler = ARTLog(capturingOutput: true) let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let (keyData, ivData, messages) = AblyTests.loadCryptoTestData(cryptoTest) let testMessage = messages[0] - let cipherParams = ARTCipherParams(algorithm: "aes", key: keyData, iv: ivData) + let cipherParams = ARTCipherParams(algorithm: "aes", key: keyData as ARTCipherKeyCompatible, iv: ivData) let channelOptions = ARTChannelOptions(cipher: cipherParams) let channel = client.channels.get("test", options: channelOptions) let transport = client.transport as! TestProxyTransport transport.beforeProcessingSentMessage = { protocolMessage in - if protocolMessage.action == .Message { + if protocolMessage.action == .message { expect(protocolMessage.messages![0].data as? String).to(equal(testMessage.encrypted.data)) expect(protocolMessage.messages![0].encoding).to(equal(testMessage.encrypted.encoding)) } } transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Message { - expect(protocolMessage.messages![0].data as? NSObject).to(equal(AblyTests.base64ToData(testMessage.encrypted.data))) + if protocolMessage.action == .message { + expect(protocolMessage.messages![0].data as? NSObject).to(equal(AblyTests.base64ToData(testMessage.encrypted.data) as NSObject?)) expect(protocolMessage.messages![0].encoding).to(equal("utf-8/cipher+aes-\(cryptoTest == CryptoTest.aes128 ? "128" : "256")-cbc")) // Force an error decoding a message protocolMessage.messages![0].encoding = "bad_encoding_type" @@ -2570,7 +2573,7 @@ class RealtimeClientChannel: QuickSpec { let partlyDone = AblyTests.splitDone(2, done: done) channel.subscribe(testMessage.encoded.name) { message in - expect(message.data as? NSObject).to(equal(AblyTests.base64ToData(testMessage.encrypted.data))) + expect(message.data as? NSObject).to(equal(AblyTests.base64ToData(testMessage.encrypted.data) as NSObject?)) let logs = options.logHandler.captured let line = logs.reduce("") { $0 + "; " + $1.toString() } //Reduce in one line @@ -2580,7 +2583,7 @@ class RealtimeClientChannel: QuickSpec { partlyDone() } - channel.on(.Update) { stateChange in + channel.on(.update) { stateChange in guard let error = stateChange?.reason else { return } @@ -2604,23 +2607,23 @@ class RealtimeClientChannel: QuickSpec { options.autoConnect = false options.logHandler = ARTLog(capturingOutput: true) let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } - let channelOptions = ARTChannelOptions(cipher: ["key":ARTCrypto.generateRandomKey()]) + let channelOptions = ARTChannelOptions(cipher: ["key":ARTCrypto.generateRandomKey()] as ARTCipherParamsCompatible) let channel = client.channels.get("test", options: channelOptions) let expectedMessage = ["key":1] - let expectedData = try! NSJSONSerialization.dataWithJSONObject(expectedMessage, options: NSJSONWritingOptions(rawValue: 0)) + let expectedData = try! JSONSerialization.data(withJSONObject: expectedMessage, options: JSONSerialization.WritingOptions(rawValue: 0)) let transport = client.transport as! TestProxyTransport transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Message { + if protocolMessage.action == .message { let messageReceived = protocolMessage.messages![0] // Replacement: `json/utf-8/cipher+aes-256-cbc/base64` to `invalid/cipher+aes-256-cbc/base64` - let newEncoding = "invalid" + messageReceived.encoding!.substringFromIndex("json/utf-8".endIndex) + let newEncoding = "invalid" + messageReceived.encoding!.substring(from: "json/utf-8".endIndex) messageReceived.encoding = newEncoding } } @@ -2628,7 +2631,7 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.subscribe { message in // Last decoding failed: NSData -> JSON object, so... - expect(message.data as? NSData).to(equal(expectedData)) + expect(message.data as? NSData).to(equal(expectedData as NSData?)) expect(message.encoding).to(equal("invalid")) let logs = options.logHandler.captured @@ -2748,9 +2751,9 @@ class RealtimeClientChannel: QuickSpec { let channelRealtime = realtime.channels.get("test") let queryRealtime = ARTRealtimeHistoryQuery() - queryRealtime.start = NSDate() - queryRealtime.end = NSDate() - queryRealtime.direction = .Forwards + queryRealtime.start = NSDate() as Date + queryRealtime.end = NSDate() as Date + queryRealtime.direction = .forwards queryRealtime.limit = 50 let queryRest = queryRealtime as ARTDataQuery @@ -2791,7 +2794,7 @@ class RealtimeClientChannel: QuickSpec { try channel.history(query, callback: { _, _ in }) } catch let error as NSError { - if error.code == ARTRealtimeHistoryError.NotAttached.rawValue { + if (error as! ARTErrorInfo).code == ARTRealtimeHistoryError.notAttached.rawValue { return } fail("Shouldn't raise a global error, got \(error)") @@ -2818,7 +2821,7 @@ class RealtimeClientChannel: QuickSpec { query.untilAttach = caseItem.untilAttach channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in try! channel.history(query) { _, errorInfo in @@ -2827,7 +2830,7 @@ class RealtimeClientChannel: QuickSpec { } } - let queryString = testHTTPExecutor.requests.last!.URL!.query + let queryString = testHTTPExecutor.requests.last!.url!.query if query.untilAttach { expect(queryString).to(contain("fromSerial=\(channel.attachSerial!)")) @@ -2849,7 +2852,7 @@ class RealtimeClientChannel: QuickSpec { let channel1 = client1.channels.get("test") channel1.attach() - expect(channel1.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel1.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) var messages = [ARTMessage]() for i in 0..<20 { @@ -2865,7 +2868,7 @@ class RealtimeClientChannel: QuickSpec { client2.connect() let channel2 = client2.channels.get("test") channel2.attach() - expect(channel2.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel2.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) var counter = 20 channel2.subscribe { message in @@ -2891,8 +2894,8 @@ class RealtimeClientChannel: QuickSpec { try! channel2.history(query) { result, errorInfo in expect(result!.items).to(haveCount(20)) expect(result!.hasNext).to(beFalse()) - expect((result!.items.first as? ARTMessage)?.data as? String).to(equal("message 19")) - expect((result!.items.last as? ARTMessage)?.data as? String).to(equal("message 0")) + expect(result!.items.first?.data as? String).to(equal("message 19")) + expect(result!.items.last?.data as? String).to(equal("message 0")) done() } } @@ -2915,12 +2918,10 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.history { result, _ in - expect(result).to(beAKindOf(ARTPaginatedResult)) + expect(result).to(beAKindOf(ARTPaginatedResult.self)) expect(result!.items).to(haveCount(1)) expect(result!.hasNext).to(beFalse()) - // Obj-C generics get lost in translation - //Something related: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006792.html - let messages = result!.items as! [ARTMessage] + let messages = result!.items expect(messages[0].data as? String).to(equal("message")) done() } @@ -2938,7 +2939,7 @@ class RealtimeClientChannel: QuickSpec { let channel1 = client1.channels.get("test") channel1.attach() - expect(channel1.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel1.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) var messages = [ARTMessage]() for i in 0..<20 { @@ -2953,7 +2954,7 @@ class RealtimeClientChannel: QuickSpec { let channel2 = client2.channels.get("test") channel2.attach() - expect(channel2.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel2.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) let query = ARTRealtimeHistoryQuery() query.limit = 10 @@ -2963,15 +2964,15 @@ class RealtimeClientChannel: QuickSpec { expect(result!.items).to(haveCount(10)) expect(result!.hasNext).to(beTrue()) expect(result!.isLast).to(beFalse()) - expect((result!.items.first! as! ARTMessage).data as? String).to(equal("message 19")) - expect((result!.items.last! as! ARTMessage).data as? String).to(equal("message 10")) + expect((result!.items.first! ).data as? String).to(equal("message 19")) + expect((result!.items.last! ).data as? String).to(equal("message 10")) result!.next { result, errorInfo in expect(result!.items).to(haveCount(10)) expect(result!.hasNext).to(beFalse()) expect(result!.isLast).to(beTrue()) - expect((result!.items.first! as! ARTMessage).data as? String).to(equal("message 9")) - expect((result!.items.last! as! ARTMessage).data as? String).to(equal("message 0")) + expect((result!.items.first! ).data as? String).to(equal("message 9")) + expect((result!.items.last! ).data as? String).to(equal("message 0")) done() } } @@ -2990,7 +2991,7 @@ class RealtimeClientChannel: QuickSpec { } } - channel.on(.Attached) { _ in + channel.on(.attached) { _ in fail("Should not be called") } defer { @@ -3000,10 +3001,10 @@ class RealtimeClientChannel: QuickSpec { var hook: AspectToken? waitUntil(timeout: testTimeout) { done in let attachedMessage = ARTProtocolMessage() - attachedMessage.action = .Attached + attachedMessage.action = .attached attachedMessage.channel = "test" - hook = channel.testSuite_injectIntoMethodAfter(#selector(channel.onChannelMessage(_:))) { + hook = channel.testSuite_injectIntoMethod(after: #selector(channel.onChannelMessage(_:))) { done() } @@ -3012,18 +3013,18 @@ class RealtimeClientChannel: QuickSpec { } hook!.remove() expect(channel.errorReason).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) waitUntil(timeout: testTimeout) { done in let attachedMessageWithError = AblyTests.newErrorProtocolMessage() - attachedMessageWithError.action = .Attached + attachedMessageWithError.action = .attached attachedMessageWithError.channel = "test" - channel.once(.Update) { stateChange in + channel.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); done(); return } - expect(stateChange.event).to(equal(ARTChannelEvent.Update)) + expect(stateChange.event).to(equal(ARTChannelEvent.update)) expect(stateChange.reason).to(beIdenticalTo(attachedMessageWithError.error)) expect(channel.errorReason).to(beIdenticalTo(stateChange.reason)) done() @@ -3032,7 +3033,7 @@ class RealtimeClientChannel: QuickSpec { // Inject additional ATTACHED action with an error client.transport?.receive(attachedMessageWithError) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) } // RTL13 @@ -3051,7 +3052,7 @@ class RealtimeClientChannel: QuickSpec { } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return @@ -3059,10 +3060,10 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let detachedMessageWithError = AblyTests.newErrorProtocolMessage() - detachedMessageWithError.action = .Detached + detachedMessageWithError.action = .detached detachedMessageWithError.channel = "foo" - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -3074,7 +3075,7 @@ class RealtimeClientChannel: QuickSpec { transport.receive(detachedMessageWithError) } - expect(transport.protocolMessagesSent.filter{ $0.action == .Attach }).to(haveCount(2)) + expect(transport.protocolMessagesSent.filter{ $0.action == .attach }).to(haveCount(2)) } // RTL13a @@ -3084,7 +3085,7 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("foo") waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -3099,10 +3100,10 @@ class RealtimeClientChannel: QuickSpec { ARTDefault.setRealtimeRequestTimeout(1.0) // Timeout - transport.actionsIgnored += [.Attached] + transport.actionsIgnored += [.attached] waitUntil(timeout: testTimeout) { done in - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in expect(stateChange?.reason?.message).to(contain("timed out")) done() } @@ -3113,10 +3114,10 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let detachedMessageWithError = AblyTests.newErrorProtocolMessage() - detachedMessageWithError.action = .Detached + detachedMessageWithError.action = .detached detachedMessageWithError.channel = "foo" - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -3128,7 +3129,7 @@ class RealtimeClientChannel: QuickSpec { transport.receive(detachedMessageWithError) } - expect(transport.protocolMessagesSent.filter{ $0.action == .Attach }).to(haveCount(2)) + expect(transport.protocolMessagesSent.filter{ $0.action == .attach }).to(haveCount(2)) } // RTL13b @@ -3153,14 +3154,14 @@ class RealtimeClientChannel: QuickSpec { let previousRealtimeRequestTimeout = ARTDefault.realtimeRequestTimeout() defer { ARTDefault.setRealtimeRequestTimeout(previousRealtimeRequestTimeout) } ARTDefault.setRealtimeRequestTimeout(1.0) - transport.actionsIgnored = [.Attached] + transport.actionsIgnored = [.attached] let detachedMessageWithError = AblyTests.newErrorProtocolMessage() - detachedMessageWithError.action = .Detached + detachedMessageWithError.action = .detached detachedMessageWithError.channel = "foo" waitUntil(timeout: testTimeout) { done in - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -3173,7 +3174,7 @@ class RealtimeClientChannel: QuickSpec { } waitUntil(timeout: testTimeout) { done in - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -3185,9 +3186,9 @@ class RealtimeClientChannel: QuickSpec { let start = NSDate() waitUntil(timeout: testTimeout) { done in - channel.once(.Attaching) { _ in + channel.once(.attaching) { _ in let end = NSDate() - expect(start.dateByAddingTimeInterval(options.channelRetryTimeout)).to(beCloseTo(end, within: 0.5)) + expect(start.addingTimeInterval(options.channelRetryTimeout)).to(beCloseTo(end, within: 0.5)) done() } } @@ -3202,17 +3203,17 @@ class RealtimeClientChannel: QuickSpec { let channel = client.channels.get("foo") let detachedMessageWithError = AblyTests.newErrorProtocolMessage() - detachedMessageWithError.action = .Detached + detachedMessageWithError.action = .detached detachedMessageWithError.channel = "foo" waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in expect(stateChange?.reason).to(beNil()) client.transport?.receive(detachedMessageWithError) partialDone() } - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); partialDone(); return } @@ -3221,7 +3222,7 @@ class RealtimeClientChannel: QuickSpec { // Check retry let start = NSDate() - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in let end = NSDate() expect(start).to(beCloseTo(end, within: 0.5)) expect(stateChange?.reason).to(beNil()) @@ -3253,12 +3254,12 @@ class RealtimeClientChannel: QuickSpec { defer { ARTDefault.setRealtimeRequestTimeout(previousRealtimeRequestTimeout) } ARTDefault.setRealtimeRequestTimeout(1.0) - transport.actionsIgnored = [.Attached] + transport.actionsIgnored = [.attached] let detachedMessageWithError = AblyTests.newErrorProtocolMessage() - detachedMessageWithError.action = .Detached + detachedMessageWithError.action = .detached detachedMessageWithError.channel = "foo" waitUntil(timeout: testTimeout) { done in - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -3269,7 +3270,7 @@ class RealtimeClientChannel: QuickSpec { transport.receive(detachedMessageWithError) } waitUntil(timeout: testTimeout) { done in - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -3279,12 +3280,12 @@ class RealtimeClientChannel: QuickSpec { } } - channel.once(.Attaching) { _ in + channel.once(.attaching) { _ in fail("Should cancel the re-attach") } client.simulateSuspended(beforeSuspension: { done in - channel.once(.Suspended) { _ in + channel.once(.suspended) { _ in done() } }) @@ -3306,10 +3307,10 @@ class RealtimeClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in let errorProtocolMessage = AblyTests.newErrorProtocolMessage() - errorProtocolMessage.action = .Error + errorProtocolMessage.action = .error errorProtocolMessage.channel = "foo" - channel.once(.Failed) { stateChange in + channel.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -3321,7 +3322,7 @@ class RealtimeClientChannel: QuickSpec { client.transport?.receive(errorProtocolMessage) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) } } @@ -3332,18 +3333,18 @@ class RealtimeClientChannel: QuickSpec { options.autoConnect = false let clientSender = ARTRealtime(options: options) - clientSender.setTransportClass(TestProxyTransport.self) + clientSender.setTransport(TestProxyTransport.self) defer { clientSender.close() } clientSender.connect() let clientReceiver = ARTRealtime(options: options) - clientReceiver.setTransportClass(TestProxyTransport.self) + clientReceiver.setTransport(TestProxyTransport.self) defer { clientReceiver.close() } clientReceiver.connect() let key = ARTCrypto.generateRandomKey() - let sender = clientSender.channels.get("test", options: ARTChannelOptions(cipherKey: key)) - let receiver = clientReceiver.channels.get("test", options: ARTChannelOptions(cipherKey: key)) + let sender = clientSender.channels.get("test", options: ARTChannelOptions(cipherKey: key as ARTCipherKeyCompatible)) + let receiver = clientReceiver.channels.get("test", options: ARTChannelOptions(cipherKey: key as ARTCipherKeyCompatible)) var received = [ARTMessage]() @@ -3368,7 +3369,7 @@ class RealtimeClientChannel: QuickSpec { sender.publish("second", data: "second data") { _ in done() } } } - if receiver.state != .Detached { + if receiver.state != .detached { fail("receiver should be detached") return } @@ -3393,7 +3394,7 @@ class RealtimeClientChannel: QuickSpec { expect(received[1].data as? NSString).to(equal("third data")) let senderTransport = clientSender.transport as! TestProxyTransport - let senderMessages = senderTransport.protocolMessagesSent.filter({ $0.action == .Message }) + let senderMessages = senderTransport.protocolMessagesSent.filter({ $0.action == .message }) for protocolMessage in senderMessages { for message in protocolMessage.messages! { expect(message.data! as? String).toNot(equal("\(message.name!) data")) @@ -3402,10 +3403,10 @@ class RealtimeClientChannel: QuickSpec { } let receiverTransport = clientReceiver.transport as! TestProxyTransport - let receiverMessages = receiverTransport.protocolMessagesReceived.filter({ $0.action == .Message }) + let receiverMessages = receiverTransport.protocolMessagesReceived.filter({ $0.action == .message }) for protocolMessage in receiverMessages { for message in protocolMessage.messages! { - expect(message.data! as? NSObject).toNot(equal("\(message.name!) data")) + expect(message.data! as? NSObject).toNot(equal("\(message.name!) data" as NSObject?)) expect(message.encoding).to(equal("utf-8/cipher+aes-256-cbc")) } } diff --git a/Spec/RealtimeClientChannels.swift b/Spec/RealtimeClientChannels.swift index 7db6faecc..32d04dfd7 100644 --- a/Spec/RealtimeClientChannels.swift +++ b/Spec/RealtimeClientChannels.swift @@ -11,9 +11,9 @@ import Quick import Nimble // Swift isn't yet smart enough to do this automatically when bridging Objective-C APIs -extension ARTRealtimeChannels: SequenceType { - public func generate() -> NSFastGenerator { - return NSFastGenerator(self) +extension ARTRealtimeChannels: Sequence { + public func makeIterator() -> NSFastEnumerationIterator { + return NSFastEnumerationIterator(self) } } @@ -94,7 +94,7 @@ class RealtimeClientChannels: QuickSpec { waitUntil(timeout: testTimeout) { done in client.channels.release("test") { errorInfo in expect(errorInfo).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) done() } } diff --git a/Spec/RealtimeClientConnection.swift b/Spec/RealtimeClientConnection.swift index b6a6d507e..92b6e8b97 100644 --- a/Spec/RealtimeClientConnection.swift +++ b/Spec/RealtimeClientConnection.swift @@ -11,7 +11,7 @@ import Quick import Nimble import SwiftyJSON -func countChannels(channels: ARTRealtimeChannels) -> Int { +func countChannels(_ channels: ARTRealtimeChannels) -> Int { var i = 0 for _ in channels { i += 1 @@ -30,7 +30,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -47,7 +47,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -57,10 +57,10 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: AblyTests.checkError(errorInfo, withAlternative: "Failed state") done() - case .Connected: + case .connected: if let transport = client.transport as? TestProxyTransport, let query = transport.lastUrl?.query { expect(query).to(haveParam("key", withValue: options.key ?? "")) expect(query).to(haveParam("echo", withValue: "true")) @@ -85,7 +85,7 @@ class RealtimeClientConnection: QuickSpec { options.echoMessages = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -95,10 +95,10 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: AblyTests.checkError(errorInfo, withAlternative: "Failed state") done() - case .Connected: + case .connected: if let transport = client.transport as? TestProxyTransport, let query = transport.lastUrl?.query { expect(query).to(haveParam("accessToken", withValue: client.auth.tokenDetails?.token ?? "")) expect(query).to(haveParam("echo", withValue: "false")) @@ -134,7 +134,7 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: connected = true default: break @@ -157,7 +157,7 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: if waiting { XCTFail("Expected to be disconnected") } @@ -166,7 +166,7 @@ class RealtimeClientConnection: QuickSpec { break } } - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { + DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(2)) { waiting = false client.connect() } @@ -180,7 +180,7 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connecting) { _ in + client.connection.once(.connecting) { _ in guard let webSocketTransport = client.transport as? ARTWebSocketTransport else { fail("Transport should be of type ARTWebSocketTransport"); done() return @@ -199,7 +199,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() waitUntil(timeout: testTimeout) { done in @@ -208,10 +208,10 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: AblyTests.checkError(errorInfo, withAlternative: "Failed state") done() - case .Connected: + case .connected: if let transport = client.transport as? TestProxyTransport, let query = transport.lastUrl?.query { expect(query).to(haveParam("lib", withValue: "ios-1.0.4")) } @@ -251,11 +251,11 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connecting: + case .connecting: if !alreadyDisconnected { events += [state] } - case .Connected: + case .connected: if alreadyClosed { delay(0) { client.onSuspended() @@ -268,19 +268,19 @@ class RealtimeClientConnection: QuickSpec { client.onDisconnected() } } - case .Disconnected: + case .disconnected: events += [state] alreadyDisconnected = true - case .Suspended: + case .suspended: events += [state] client.onError(AblyTests.newErrorProtocolMessage()) - case .Closing: + case .closing: events += [state] - case .Closed: + case .closed: events += [state] alreadyClosed = true client.connect() - case .Failed: + case .failed: events += [state] expect(errorInfo).toNot(beNil(), description: "Error is nil") connection.off() @@ -298,14 +298,14 @@ class RealtimeClientConnection: QuickSpec { return } - expect(events[0].rawValue).to(equal(ARTRealtimeConnectionState.Initialized.rawValue), description: "Should be INITIALIZED state") - expect(events[1].rawValue).to(equal(ARTRealtimeConnectionState.Connecting.rawValue), description: "Should be CONNECTING state") - expect(events[2].rawValue).to(equal(ARTRealtimeConnectionState.Connected.rawValue), description: "Should be CONNECTED state") - expect(events[3].rawValue).to(equal(ARTRealtimeConnectionState.Disconnected.rawValue), description: "Should be DISCONNECTED state") - expect(events[4].rawValue).to(equal(ARTRealtimeConnectionState.Closing.rawValue), description: "Should be CLOSING state") - expect(events[5].rawValue).to(equal(ARTRealtimeConnectionState.Closed.rawValue), description: "Should be CLOSED state") - expect(events[6].rawValue).to(equal(ARTRealtimeConnectionState.Suspended.rawValue), description: "Should be SUSPENDED state") - expect(events[7].rawValue).to(equal(ARTRealtimeConnectionState.Failed.rawValue), description: "Should be FAILED state") + expect(events[0].rawValue).to(equal(ARTRealtimeConnectionState.initialized.rawValue), description: "Should be INITIALIZED state") + expect(events[1].rawValue).to(equal(ARTRealtimeConnectionState.connecting.rawValue), description: "Should be CONNECTING state") + expect(events[2].rawValue).to(equal(ARTRealtimeConnectionState.connected.rawValue), description: "Should be CONNECTED state") + expect(events[3].rawValue).to(equal(ARTRealtimeConnectionState.disconnected.rawValue), description: "Should be DISCONNECTED state") + expect(events[4].rawValue).to(equal(ARTRealtimeConnectionState.closing.rawValue), description: "Should be CLOSING state") + expect(events[5].rawValue).to(equal(ARTRealtimeConnectionState.closed.rawValue), description: "Should be CLOSED state") + expect(events[6].rawValue).to(equal(ARTRealtimeConnectionState.suspended.rawValue), description: "Should be SUSPENDED state") + expect(events[7].rawValue).to(equal(ARTRealtimeConnectionState.failed.rawValue), description: "Should be FAILED state") } // RTN4h @@ -315,30 +315,30 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in fail("Should not emit a Connected state") } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Update) { stateChange in + client.connection.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } expect(stateChange.reason).to(beNil()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) - expect(stateChange.current).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) + expect(stateChange.current).to(equal(ARTRealtimeConnectionState.connected)) expect(stateChange.current).to(equal(stateChange.previous)) done() } let authMessage = ARTProtocolMessage() - authMessage.action = .Auth + authMessage.action = .auth client.transport?.receive(authMessage) } } @@ -359,9 +359,9 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connecting: + case .connecting: events += [state] - case .Connected: + case .connected: events += [state] done() default: @@ -377,8 +377,8 @@ class RealtimeClientConnection: QuickSpec { return } - expect(events[0].rawValue).to(equal(ARTRealtimeConnectionState.Connecting.rawValue), description: "Should be CONNECTING state") - expect(events[1].rawValue).to(equal(ARTRealtimeConnectionState.Connected.rawValue), description: "Should be CONNECTED state") + expect(events[0].rawValue).to(equal(ARTRealtimeConnectionState.connecting.rawValue), description: "Should be CONNECTING state") + expect(events[1].rawValue).to(equal(ARTRealtimeConnectionState.connected.rawValue), description: "Should be CONNECTED state") } // RTN4c @@ -394,11 +394,11 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: connection.close() - case .Closing: + case .closing: events += [state] - case .Closed: + case .closed: events += [state] done() default: @@ -413,8 +413,8 @@ class RealtimeClientConnection: QuickSpec { return } - expect(events[0].rawValue).to(equal(ARTRealtimeConnectionState.Closing.rawValue), description: "Should be CLOSING state") - expect(events[1].rawValue).to(equal(ARTRealtimeConnectionState.Closed.rawValue), description: "Should be CLOSED state") + expect(events[0].rawValue).to(equal(ARTRealtimeConnectionState.closing.rawValue), description: "Should be CLOSING state") + expect(events[1].rawValue).to(equal(ARTRealtimeConnectionState.closed.rawValue), description: "Should be CLOSED state") } // RTN4d @@ -424,7 +424,7 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } let connection = client.connection - expect(connection.state.rawValue).to(equal(ARTRealtimeConnectionState.Initialized.rawValue), description: "Missing INITIALIZED state") + expect(connection.state.rawValue).to(equal(ARTRealtimeConnectionState.initialized.rawValue), description: "Missing INITIALIZED state") waitUntil(timeout: testTimeout) { done in connection.on { stateChange in @@ -432,10 +432,10 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connecting: - expect(connection.state.rawValue).to(equal(ARTRealtimeConnectionState.Connecting.rawValue), description: "Missing CONNECTING state") - case .Connected: - expect(connection.state.rawValue).to(equal(ARTRealtimeConnectionState.Connected.rawValue), description: "Missing CONNECTED state") + case .connecting: + expect(connection.state.rawValue).to(equal(ARTRealtimeConnectionState.connecting.rawValue), description: "Missing CONNECTING state") + case .connected: + expect(connection.state.rawValue).to(equal(ARTRealtimeConnectionState.connected.rawValue), description: "Missing CONNECTED state") done() default: break @@ -453,14 +453,14 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(ARTRealtimeConnectionEvent.Connected) { stateChange in + client.connection.once(ARTRealtimeConnectionEvent.connected) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is empty"); done() return } - expect(stateChange).to(beAKindOf(ARTConnectionStateChange)) - expect(stateChange.current).to(equal(ARTRealtimeConnectionState.Connected)) - expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange).to(beAKindOf(ARTConnectionStateChange.self)) + expect(stateChange.current).to(equal(ARTRealtimeConnectionState.connected)) + expect(stateChange.previous).to(equal(ARTRealtimeConnectionState.connecting)) done() } client.connect() @@ -483,11 +483,11 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let reason = stateChange.reason switch state { - case .Connected: - expect(stateChange.event).to(equal(ARTRealtimeConnectionEvent.Connected)) + case .connected: + expect(stateChange.event).to(equal(ARTRealtimeConnectionEvent.connected)) client.onError(AblyTests.newErrorProtocolMessage()) - case .Failed: - expect(stateChange.event).to(equal(ARTRealtimeConnectionEvent.Failed)) + case .failed: + expect(stateChange.event).to(equal(ARTRealtimeConnectionEvent.failed)) errorInfo = reason done() default: @@ -507,7 +507,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -516,12 +516,12 @@ class RealtimeClientConnection: QuickSpec { guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } - guard let originalConnectedMessage = transport.protocolMessagesReceived.filter({ $0.action == .Connected }).first else { + guard let originalConnectedMessage = transport.protocolMessagesReceived.filter({ $0.action == .connected }).first else { fail("First CONNECTED message not received"); return } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Update) { stateChange in + client.connection.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } @@ -530,12 +530,12 @@ class RealtimeClientConnection: QuickSpec { } expect(error.code) == 1234 expect(error.message) == "fabricated error" - expect(stateChange.event).to(equal(ARTRealtimeConnectionEvent.Update)) + expect(stateChange.event).to(equal(ARTRealtimeConnectionEvent.update)) done() } let connectedMessageWithError = originalConnectedMessage - connectedMessageWithError.error = ARTErrorInfo.createWithCode(1234, message: "fabricated error") + connectedMessageWithError.error = ARTErrorInfo.create(withCode: 1234, message: "fabricated error") client.transport?.receive(connectedMessageWithError) } } @@ -582,7 +582,7 @@ class RealtimeClientConnection: QuickSpec { let total = max*max - max for client in disposable { let channel = client.channels.get(channelName) - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) channel.subscribe { message in expect(message.data as? String).to(equal("message_string")) @@ -608,7 +608,7 @@ class RealtimeClientConnection: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose() @@ -621,14 +621,14 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let error = stateChange.reason expect(error).to(beNil()) - if state == .Connected && error == nil { + if state == .connected && error == nil { done() } } } if let webSocketTransport = client.transport as? ARTWebSocketTransport { - expect(webSocketTransport.state).to(equal(ARTRealtimeTransportState.Opened)) + expect(webSocketTransport.state).to(equal(ARTRealtimeTransportState.opened)) } else { XCTFail("WebSocket is not the default transport") @@ -636,7 +636,7 @@ class RealtimeClientConnection: QuickSpec { if let transport = client.transport as? TestProxyTransport { // CONNECTED ProtocolMessage - expect(transport.protocolMessagesReceived.map{ $0.action }).to(contain(ARTProtocolMessageAction.Connected)) + expect(transport.protocolMessagesReceived.map{ $0.action }).to(contain(ARTProtocolMessageAction.connected)) } else { XCTFail("MockTransport is not working") @@ -654,7 +654,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false options.clientId = "client_string" let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -667,11 +667,11 @@ class RealtimeClientConnection: QuickSpec { let transport = client.transport as! TestProxyTransport - guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .Message }).last else { + guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .message }).last else { XCTFail("No MESSAGE action was sent"); return } - guard let receivedAck = transport.protocolMessagesReceived.filter({ $0.action == .Ack }).last else { + guard let receivedAck = transport.protocolMessagesReceived.filter({ $0.action == .ack }).last else { XCTFail("No ACK action was received"); return } @@ -683,7 +683,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false options.clientId = "client_string" let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -692,7 +692,7 @@ class RealtimeClientConnection: QuickSpec { let stateChange = stateChange! let state = stateChange.current let error = stateChange.reason - if state == .Connected { + if state == .connected { let channel = client.channels.get("test") channel.attach() { error in expect(error).to(beNil()) @@ -707,11 +707,11 @@ class RealtimeClientConnection: QuickSpec { let transport = client.transport as! TestProxyTransport - guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .Presence }).last else { + guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .presence }).last else { XCTFail("No PRESENCE action was sent"); return } - guard let receivedAck = transport.protocolMessagesReceived.filter({ $0.action == .Ack }).last else { + guard let receivedAck = transport.protocolMessagesReceived.filter({ $0.action == .ack }).last else { XCTFail("No ACK action was received"); return } @@ -723,7 +723,7 @@ class RealtimeClientConnection: QuickSpec { options.token = getTestToken(key: options.key, capability: "{ \"\(ARTChannels_getChannelNamePrefix!())-test\":[\"subscribe\"] }") options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -736,11 +736,11 @@ class RealtimeClientConnection: QuickSpec { let transport = client.transport as! TestProxyTransport - guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .Message }).last else { + guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .message }).last else { XCTFail("No MESSAGE action was sent"); return } - guard let receivedNack = transport.protocolMessagesReceived.filter({ $0.action == .Nack }).last else { + guard let receivedNack = transport.protocolMessagesReceived.filter({ $0.action == .nack }).last else { XCTFail("No NACK action was received"); return } @@ -752,7 +752,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false options.clientId = "client_string" let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -761,7 +761,7 @@ class RealtimeClientConnection: QuickSpec { let stateChange = stateChange! let state = stateChange.current let error = stateChange.reason - if state == .Connected { + if state == .connected { let channel = client.channels.get("test") channel.attach() { error in expect(error).to(beNil()) @@ -776,11 +776,11 @@ class RealtimeClientConnection: QuickSpec { let transport = client.transport as! TestProxyTransport - guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .Presence }).last else { + guard let publishedMessage = transport.protocolMessagesSent.filter({ $0.action == .presence }).last else { XCTFail("No PRESENCE action was sent"); return } - guard let receivedNack = transport.protocolMessagesReceived.filter({ $0.action == .Nack }).last else { + guard let receivedNack = transport.protocolMessagesReceived.filter({ $0.action == .nack }).last else { XCTFail("No NACK action was received"); return } @@ -795,7 +795,7 @@ class RealtimeClientConnection: QuickSpec { class TotalMessages { static var expected: Int32 = 0 static var succeeded: Int32 = 0 - private init() {} + fileprivate init() {} } it("should contain unique serially incrementing msgSerial along with the count") { @@ -803,7 +803,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false options.clientId = "client_string" let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } @@ -835,8 +835,8 @@ class RealtimeClientConnection: QuickSpec { } let transport = client.transport as! TestProxyTransport - let acks = transport.protocolMessagesReceived.filter({ $0.action == .Ack }) - let nacks = transport.protocolMessagesReceived.filter({ $0.action == .Nack }) + let acks = transport.protocolMessagesReceived.filter({ $0.action == .ack }) + let nacks = transport.protocolMessagesReceived.filter({ $0.action == .nack }) if acks.count != 2 { fail("Received invalid number of ACK responses: \(acks.count)") @@ -862,7 +862,7 @@ class RealtimeClientConnection: QuickSpec { it("should continue incrementing msgSerial serially if the connection resumes successfully") { let options = AblyTests.commonAppSetup() options.clientId = "tester" - options.tokenDetails = getTestTokenDetails(key: options.key!, ttl: 5.0, clientId: options.clientId) + options.tokenDetails = getTestTokenDetails(key: options.key!, clientId: options.clientId, ttl: 5.0) let client = AblyTests.newRealtime(options) defer { client.dispose(); client.close() } @@ -896,7 +896,7 @@ class RealtimeClientConnection: QuickSpec { expect(client.msgSerial) == 5 waitUntil(timeout: testTimeout) { done in - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in expect(stateChange?.reason).toNot(beNil()) // Token expired done() @@ -923,8 +923,8 @@ class RealtimeClientConnection: QuickSpec { guard let reconnectedTransport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } - let acks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .Ack }) - let nacks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .Nack }) + let acks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .ack }) + let nacks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .nack }) if acks.count != 1 { fail("Received invalid number of ACK responses: \(acks.count)") @@ -983,10 +983,10 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Disconnected) { _ in + client.connection.once(.disconnected) { _ in partialDone() } - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in channel.attach() partialDone() } @@ -1013,8 +1013,8 @@ class RealtimeClientConnection: QuickSpec { guard let reconnectedTransport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } - let acks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .Ack }) - let nacks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .Nack }) + let acks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .ack }) + let nacks = reconnectedTransport.protocolMessagesReceived.filter({ $0.action == .nack }) if acks.count != 1 { fail("Received invalid number of ACK responses: \(acks.count)") @@ -1043,13 +1043,13 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false options.clientId = "client_string" let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("channel") let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Ack, .Nack] + transport.actionsIgnored += [.ack, .nack] waitUntil(timeout: testTimeout) { done in channel.attach() { error in @@ -1081,13 +1081,13 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false options.clientId = "client_string" let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("channel") let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Ack, .Nack] + transport.actionsIgnored += [.ack, .nack] waitUntil(timeout: testTimeout) { done in channel.attach() { error in @@ -1109,7 +1109,7 @@ class RealtimeClientConnection: QuickSpec { options.autoConnect = false options.disconnectedRetryTimeout = 0.1 let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose() @@ -1119,7 +1119,7 @@ class RealtimeClientConnection: QuickSpec { let channel = client.channels.get("channel") let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Ack, .Nack] + transport.actionsIgnored += [.ack, .nack] waitUntil(timeout: testTimeout) { done in channel.attach() { _ in @@ -1143,10 +1143,10 @@ class RealtimeClientConnection: QuickSpec { // Wait until the message is pushed to Ably first delay(1.0) { - client.connection.once(.Disconnected) { _ in + client.connection.once(.disconnected) { _ in partialDone() } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(client.connection.id).toNot(equal(oldConnectionId)) partialDone() } @@ -1180,11 +1180,11 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason expect(errorInfo).to(beNil()) - if state == .Connected { + if state == .connected { expect(connection.id).toNot(beNil()) done() } - else if state == .Connecting { + else if state == .connecting { expect(connection.id).to(beNil()) } } @@ -1213,7 +1213,7 @@ class RealtimeClientConnection: QuickSpec { let stateChange = stateChange! let state = stateChange.current let errorInfo = stateChange.reason - if state == .Connected { + if state == .connected { guard let connectionId = currentConnection.id else { fail("connectionId is nil on CONNECTED") done() @@ -1260,11 +1260,11 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason expect(errorInfo).to(beNil()) - if state == .Connected { + if state == .connected { expect(connection.id).toNot(beNil()) done() } - else if state == .Connecting { + else if state == .connecting { expect(connection.key).to(beNil()) } } @@ -1292,7 +1292,7 @@ class RealtimeClientConnection: QuickSpec { let stateChange = stateChange! let state = stateChange.current let errorInfo = stateChange.reason - if state == .Connected { + if state == .connected { guard let connectionKey = currentConnection.key else { fail("connectionKey is nil on CONNECTED") done() @@ -1332,7 +1332,7 @@ class RealtimeClientConnection: QuickSpec { let stateChange = stateChange! let state = stateChange.current let errorInfo = stateChange.reason - if state == .Connected { + if state == .connected { expect(client.connection.serial).to(equal(-1)) done() } @@ -1350,7 +1350,7 @@ class RealtimeClientConnection: QuickSpec { let channel = client.channels.get("test") expect(client.connection.serial).to(equal(-1)) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) expect(client.connection.serial).to(equal(-1)) for index in 0...3 { @@ -1384,7 +1384,7 @@ class RealtimeClientConnection: QuickSpec { // Attach first to avoid bundling publishes in the same ProtocolMessage. channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) for _ in 1...5 { waitUntil(timeout: testTimeout) { done in @@ -1406,7 +1406,7 @@ class RealtimeClientConnection: QuickSpec { let recoveredClient = ARTRealtime(options: options) defer { recoveredClient.close() } - expect(recoveredClient.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(recoveredClient.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in expect(recoveredClient.connection.serial).to(equal(lastSerial)) @@ -1430,7 +1430,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in done() } } @@ -1441,7 +1441,7 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Closing) { _ in + client.connection.once(.closing) { _ in oldTransport = client.transport client.connect() newTransport = client.transport @@ -1449,7 +1449,7 @@ class RealtimeClientConnection: QuickSpec { partialDone() } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in guard let stateChange = stateChange else { fail("Missing ConnectionStateChange"); partialDone() return @@ -1472,7 +1472,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in done() } } @@ -1484,12 +1484,12 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - client.connection.once(.Closing) { _ in + client.connection.once(.closing) { _ in oldTransport = client.transport // Old connection must complete the close request weak var oldTestProxyTransport = oldTransport as? TestProxyTransport oldTestProxyTransport?.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Closed { + if protocolMessage.action == .closed { partialDone() } } @@ -1503,11 +1503,11 @@ class RealtimeClientConnection: QuickSpec { partialDone() } - client.connection.once(.Closed) { _ in + client.connection.once(.closed) { _ in fail("New connection should not receive the old connection event") } - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in partialDone() } @@ -1541,7 +1541,7 @@ class RealtimeClientConnection: QuickSpec { expect(lastStateChange).toEventuallyNot(beNil(), timeout: testTimeout) - expect(lastStateChange!.current).toEventually(equal(ARTRealtimeConnectionState.Closed), timeout: testTimeout) + expect(lastStateChange!.current).toEventually(equal(ARTRealtimeConnectionState.closed), timeout: testTimeout) } // RTN12a @@ -1549,7 +1549,7 @@ class RealtimeClientConnection: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose() @@ -1564,13 +1564,13 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: client.close() - case .Closing: - expect(transport.protocolMessagesSent.filter({ $0.action == .Close })).to(haveCount(1)) + case .closing: + expect(transport.protocolMessagesSent.filter({ $0.action == .close })).to(haveCount(1)) states += [state] - case.Closed: - expect(transport.protocolMessagesReceived.filter({ $0.action == .Closed })).to(haveCount(1)) + case.closed: + expect(transport.protocolMessagesReceived.filter({ $0.action == .closed })).to(haveCount(1)) states += [state] done() default: @@ -1583,8 +1583,8 @@ class RealtimeClientConnection: QuickSpec { fail("Invalid number of connection states. Expected CLOSING and CLOSE states") return } - expect(states[0]).to(equal(ARTRealtimeConnectionState.Closing)) - expect(states[1]).to(equal(ARTRealtimeConnectionState.Closed)) + expect(states[0]).to(equal(ARTRealtimeConnectionState.closing)) + expect(states[1]).to(equal(ARTRealtimeConnectionState.closed)) } // RTN12b @@ -1592,7 +1592,7 @@ class RealtimeClientConnection: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose() @@ -1600,7 +1600,7 @@ class RealtimeClientConnection: QuickSpec { } let transport = client.transport as! TestProxyTransport - transport.actionsIgnored += [.Closed] + transport.actionsIgnored += [.closed] var states: [ARTRealtimeConnectionState] = [] var start: NSDate? @@ -1611,15 +1611,15 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: client.close() - case .Closing: + case .closing: start = NSDate() states += [state] - case .Closed: + case .closed: end = NSDate() states += [state] - case .Disconnected: + case .disconnected: states += [state] default: break @@ -1634,8 +1634,8 @@ class RealtimeClientConnection: QuickSpec { return } - expect(states[0]).to(equal(ARTRealtimeConnectionState.Closing)) - expect(states[1]).to(equal(ARTRealtimeConnectionState.Closed)) + expect(states[0]).to(equal(ARTRealtimeConnectionState.closing)) + expect(states[1]).to(equal(ARTRealtimeConnectionState.closed)) } // RTN12c @@ -1643,7 +1643,7 @@ class RealtimeClientConnection: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose() @@ -1659,16 +1659,16 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: states += [state] client.close() - case .Closing: + case .closing: states += [state] transport.simulateIncomingAbruptlyClose() - case .Closed: + case .closed: states += [state] done() - case .Disconnected, .Suspended, .Failed: + case .disconnected, .suspended, .failed: states += [state] default: break @@ -1681,9 +1681,9 @@ class RealtimeClientConnection: QuickSpec { return } - expect(states[0]).to(equal(ARTRealtimeConnectionState.Connected)) - expect(states[1]).to(equal(ARTRealtimeConnectionState.Closing)) - expect(states[2]).to(equal(ARTRealtimeConnectionState.Closed)) + expect(states[0]).to(equal(ARTRealtimeConnectionState.connected)) + expect(states[1]).to(equal(ARTRealtimeConnectionState.closing)) + expect(states[2]).to(equal(ARTRealtimeConnectionState.closed)) } // RTN12d @@ -1696,15 +1696,15 @@ class RealtimeClientConnection: QuickSpec { client.dispose() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.onDisconnected() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Disconnected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.disconnected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) client.connection.once { stateChange in - expect(stateChange!.current).to(equal(ARTRealtimeConnectionState.Closed)) + expect(stateChange!.current).to(equal(ARTRealtimeConnectionState.closed)) partialDone() } @@ -1712,7 +1712,7 @@ class RealtimeClientConnection: QuickSpec { delay(options.disconnectedRetryTimeout + 0.5) { // Make sure the retry doesn't happen. - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closed)) partialDone() } } @@ -1728,15 +1728,15 @@ class RealtimeClientConnection: QuickSpec { client.dispose() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.onSuspended() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Suspended), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.suspended), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) client.connection.once { stateChange in - expect(stateChange!.current).to(equal(ARTRealtimeConnectionState.Closed)) + expect(stateChange!.current).to(equal(ARTRealtimeConnectionState.closed)) partialDone() } @@ -1744,7 +1744,7 @@ class RealtimeClientConnection: QuickSpec { delay(options.suspendedRetryTimeout + 0.5) { // Make sure the retry doesn't happen. - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closed)) partialDone() } } @@ -1770,32 +1770,32 @@ class RealtimeClientConnection: QuickSpec { client.ping() { error = $0 } } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Initialized)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.initialized)) ping() expect(error).toNot(beNil()) client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.onSuspended() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Suspended)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.suspended)) ping() expect(error).toNot(beNil()) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.close() - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Closing)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.closing)) ping() expect(error).toNot(beNil()) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Closed), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.closed), timeout: testTimeout) ping() expect(error).toNot(beNil()) client.onError(AblyTests.newErrorProtocolMessage()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.failed)) ping() expect(error).toNot(beNil()) } @@ -1808,8 +1808,8 @@ class RealtimeClientConnection: QuickSpec { client.ping() { error in expect(error).to(beNil()) let transport = client.transport as! TestProxyTransport - expect(transport.protocolMessagesSent.filter{ $0.action == .Heartbeat }).to(haveCount(1)) - expect(transport.protocolMessagesReceived.filter{ $0.action == .Heartbeat }).to(haveCount(1)) + expect(transport.protocolMessagesSent.filter{ $0.action == .heartbeat }).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter{ $0.action == .heartbeat }).to(haveCount(1)) done() } } @@ -1830,7 +1830,7 @@ class RealtimeClientConnection: QuickSpec { } let end = NSDate() expect(error.message).to(contain("timed out")) - expect(end.timeIntervalSinceDate(start)).to(beCloseTo(ARTDefault.realtimeRequestTimeout(), within: 1.5)) + expect(end.timeIntervalSince(start as Date)).to(beCloseTo(ARTDefault.realtimeRequestTimeout(), within: 1.5)) done() } } @@ -1841,7 +1841,7 @@ class RealtimeClientConnection: QuickSpec { // RTN14a it("should enter FAILED state when API key is invalid") { let options = AblyTests.commonAppSetup() - options.key = String(options.key!.characters.reverse()) + options.key = String(options.key!.characters.reversed()) let client = ARTRealtime(options: options) defer { client.dispose() @@ -1854,7 +1854,7 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Failed: + case .failed: expect(errorInfo).toNot(beNil()) done() default: @@ -1878,7 +1878,7 @@ class RealtimeClientConnection: QuickSpec { options.token = getTestToken(key: options.key, ttl: tokenTtl) let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) defer { client.dispose() client.close() @@ -1886,7 +1886,7 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in // Let the token expire - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in guard let reason = stateChange?.reason else { fail("Token error is missing"); done(); return } @@ -1897,13 +1897,13 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: expect(errorInfo).to(beNil()) // New token expect(client.auth.tokenDetails!.token).toNot(equal(options.token)) done() - case .Failed, .Suspended: - fail("Should not emit error (\(errorInfo))") + case .failed, .suspended: + fail("Should not emit error (\(String(describing: errorInfo)))") done() default: break @@ -1927,7 +1927,7 @@ class RealtimeClientConnection: QuickSpec { } let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) defer { client.dispose() client.close() @@ -1935,18 +1935,18 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) partialDone() } - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in guard let reason = stateChange?.reason else { fail("Reason is nil"); done(); return; } expect(reason.code) == 40142 partialDone() } - client.connection.once(.Failed) { stateChange in + client.connection.once(.failed) { stateChange in guard let reason = stateChange?.reason else { fail("Reason is nil"); done(); return; } @@ -1971,7 +1971,7 @@ class RealtimeClientConnection: QuickSpec { } let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) defer { client.dispose() client.close() @@ -1985,14 +1985,14 @@ class RealtimeClientConnection: QuickSpec { let state = stateChange.current let errorInfo = stateChange.reason switch state { - case .Connected: + case .connected: fail("Should not be connected") done() - case .Failed, .Disconnected, .Suspended: + case .failed, .disconnected, .suspended: guard let errorInfo = errorInfo else { fail("ErrorInfo is nil"); done(); return } - expect(UInt(errorInfo.code)).to(equal(ARTState.RequestTokenFailed.rawValue)) + expect(UInt(errorInfo.code)).to(equal(ARTState.requestTokenFailed.rawValue)) done() default: break @@ -2002,7 +2002,7 @@ class RealtimeClientConnection: QuickSpec { transport = client.transport as! TestProxyTransport } - let failures = transport.protocolMessagesReceived.filter({ $0.action == .Error }) + let failures = transport.protocolMessagesReceived.filter({ $0.action == .error }) if failures.count != 1 { fail("Should have only one connection request fail") @@ -2025,7 +2025,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } var start, end: NSDate? waitUntil(timeout: testTimeout) { done in - client.connection.on(.Disconnected) { stateChange in + client.connection.on(.disconnected) { stateChange in end = NSDate() expect(stateChange!.reason!.message).to(contain("timed out")) expect(client.connection.errorReason!).to(beIdenticalTo(stateChange!.reason)) @@ -2035,7 +2035,7 @@ class RealtimeClientConnection: QuickSpec { start = NSDate() } if let start = start, let end = end { - expect(end.timeIntervalSinceDate(start)).to(beCloseTo(ARTDefault.realtimeRequestTimeout(), within: 1.5)) + expect(end.timeIntervalSince(start as Date)).to(beCloseTo(ARTDefault.realtimeRequestTimeout(), within: 1.5)) } else { fail("Start date or end date are empty") @@ -2073,24 +2073,24 @@ class RealtimeClientConnection: QuickSpec { let partialDone = AblyTests.splitDone(2, done: done) var start: NSDate? - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in expect(stateChange!.reason!.message).to(contain("timed out")) - expect(stateChange!.previous).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(stateChange!.previous).to(equal(ARTRealtimeConnectionState.connecting)) expect(stateChange!.retryIn).to(beCloseTo(options.disconnectedRetryTimeout)) partialDone() start = NSDate() } - client.connection.on(.Suspended) { stateChange in + client.connection.on(.suspended) { stateChange in let end = NSDate() - expect(end.timeIntervalSinceDate(start!)).to(beCloseTo(expectedTime, within: 0.9)) + expect(end.timeIntervalSince(start! as Date)).to(beCloseTo(expectedTime, within: 0.9)) partialDone() } client.connect() - client.connection.on(.Connecting) { stateChange in - expect(stateChange!.previous).to(equal(ARTRealtimeConnectionState.Disconnected)) + client.connection.on(.connecting) { stateChange in + expect(stateChange!.previous).to(equal(ARTRealtimeConnectionState.disconnected)) totalRetry += 1 } } @@ -2104,7 +2104,7 @@ class RealtimeClientConnection: QuickSpec { options.disconnectedRetryTimeout = 0.1 options.suspendedRetryTimeout = 0.5 options.autoConnect = false - let expectedTime: NSTimeInterval = 1.0 + let expectedTime: TimeInterval = 1.0 options.authCallback = { _ in // Force a timeout @@ -2122,13 +2122,13 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.on(.Suspended) { stateChange in + client.connection.on(.suspended) { stateChange in expect(client.connection.errorReason!.message).to(contain("timed out")) let start = NSDate() - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in let end = NSDate() - expect(end.timeIntervalSinceDate(start)).to(beCloseTo(options.suspendedRetryTimeout, within: 0.5)) + expect(end.timeIntervalSince(start as Date)).to(beCloseTo(options.suspendedRetryTimeout, within: 0.5)) done() } } @@ -2141,7 +2141,7 @@ class RealtimeClientConnection: QuickSpec { options.disconnectedRetryTimeout = 0.1 options.suspendedRetryTimeout = 0.5 options.autoConnect = false - let expectedTime: NSTimeInterval = 1.0 + let expectedTime: TimeInterval = 1.0 options.authCallback = { _ in // Force a timeout @@ -2159,13 +2159,13 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.on(.Suspended) { stateChange in + client.connection.on(.suspended) { stateChange in expect(client.connection.errorReason!.message).to(contain("timed out")) let start = NSDate() - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in let end = NSDate() - expect(end.timeIntervalSinceDate(start)).to(beCloseTo(options.suspendedRetryTimeout, within: 0.5)) + expect(end.timeIntervalSince(start as Date)).to(beCloseTo(options.suspendedRetryTimeout, within: 0.5)) done() } } @@ -2176,7 +2176,7 @@ class RealtimeClientConnection: QuickSpec { // Check if the connection gets closed waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connecting) { stateChange in + client.connection.once(.connecting) { stateChange in fail("Should be closing the connection"); done(); return } delay(2.0) { @@ -2215,7 +2215,7 @@ class RealtimeClientConnection: QuickSpec { fail("Shouldn't receive the messsage") } - expect(channel1.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel1.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) let firstConnection: (id: String, key: String) = (client1.connection.id!, client1.connection.key!) @@ -2228,11 +2228,11 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client1.connection.once(.Connecting) { _ in + client1.connection.once(.connecting) { _ in expect(client1.resuming).to(beTrue()) partialDone() } - client1.connection.once(.Connected) { _ in + client1.connection.once(.connected) { _ in expect(client1.resuming).to(beFalse()) expect(client1.connection.id).toNot(equal(firstConnection.id)) expect(client1.connection.key).toNot(equal(firstConnection.key)) @@ -2240,7 +2240,7 @@ class RealtimeClientConnection: QuickSpec { } } - expect(states).toEventually(equal([.Connecting, .Connected, .Disconnected, .Connecting, .Connected]), timeout: testTimeout) + expect(states).toEventually(equal([.connecting, .connected, .disconnected, .connecting, .connected]), timeout: testTimeout) } // RTN15b @@ -2253,13 +2253,13 @@ class RealtimeClientConnection: QuickSpec { let client = AblyTests.newRealtime(options) defer { client.dispose(); client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedConnectionKey = client.connection.key! let expectedConnectionSerial = client.connection.serial client.onDisconnected() waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in let transport = client.transport as! TestProxyTransport let query = transport.lastUrl!.query expect(query).to(haveParam("resume", withValue: expectedConnectionKey)) @@ -2282,7 +2282,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedConnectionId = client.connection.id client.onDisconnected() @@ -2290,15 +2290,15 @@ class RealtimeClientConnection: QuickSpec { expect(client.queuedMessages).toEventually(haveCount(1), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in let transport = client.transport as! TestProxyTransport - let connectedPM = transport.protocolMessagesReceived.filter{ $0.action == .Connected }[0] + let connectedPM = transport.protocolMessagesReceived.filter{ $0.action == .connected }[0] expect(connectedPM.connectionId).to(equal(expectedConnectionId)) expect(stateChange!.reason).to(beNil()) done() } } - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) expect(client.queuedMessages).toEventually(haveCount(0), timeout: testTimeout) } @@ -2310,7 +2310,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedConnectionId = client.connection.id client.onDisconnected() @@ -2318,21 +2318,21 @@ class RealtimeClientConnection: QuickSpec { channel.publish(nil, data: "queued message") expect(client.queuedMessages).toEventually(haveCount(1), timeout: testTimeout) - client.connection.once(.Connecting) { _ in + client.connection.once(.connecting) { _ in let transport = client.transport as! TestProxyTransport transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Connected { - protocolMessage.error = ARTErrorInfo.createWithCode(0, message: "Injected error") + if protocolMessage.action == .connected { + protocolMessage.error = ARTErrorInfo.create(withCode: 0, message: "Injected error") } } } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange!.reason!.message).to(equal("Injected error")) expect(client.connection.errorReason).to(beIdenticalTo(stateChange!.reason)) let transport = client.transport as! TestProxyTransport - let connectedPM = transport.protocolMessagesReceived.filter{ $0.action == .Connected }[0] + let connectedPM = transport.protocolMessagesReceived.filter{ $0.action == .connected }[0] expect(connectedPM.connectionId).to(equal(expectedConnectionId)) expect(client.connection.id).to(equal(expectedConnectionId)) done() @@ -2343,13 +2343,13 @@ class RealtimeClientConnection: QuickSpec { fail("TestProxyTransport is not set"); return } transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Attached { - protocolMessage.error = ARTErrorInfo.createWithCode(0, message: "Channel injected error") + if protocolMessage.action == .attached { + protocolMessage.error = ARTErrorInfo.create(withCode: 0, message: "Channel injected error") } } waitUntil(timeout: testTimeout) { done in - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in guard let error = stateChange?.reason else { fail("Reason error is nil"); done(); return } @@ -2370,13 +2370,13 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedConnectionId = client.connection.id client.simulateLostConnectionAndState() waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in guard let error = stateChange?.reason else { fail("Connection resume failed and error should be propagated to the channel"); done(); return } @@ -2384,13 +2384,13 @@ class RealtimeClientConnection: QuickSpec { expect(error.message).to(contain("Unable to recover connection")) expect(client.connection.errorReason).to(beIdenticalTo(stateChange!.reason)) let transport = client.transport as! TestProxyTransport - let connectedPM = transport.protocolMessagesReceived.filter{ $0.action == .Connected }[0] + let connectedPM = transport.protocolMessagesReceived.filter{ $0.action == .connected }[0] expect(connectedPM.connectionId).toNot(equal(expectedConnectionId)) expect(client.connection.id).to(equal(connectedPM.connectionId)) done() } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) guard let channelError = channel.errorReason else { fail("Channel error is nil"); return } @@ -2407,28 +2407,28 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) client.onDisconnected() let protocolError = AblyTests.newErrorProtocolMessage() - client.connection.once(.Connecting) { _ in + client.connection.once(.connecting) { _ in // Resuming guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } - transport.actionsIgnored += [.Connected] + transport.actionsIgnored += [.connected] client.onError(protocolError) } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Failed) { stateChange in + client.connection.once(.failed) { stateChange in expect(stateChange!.reason).to(beIdenticalTo(protocolError.error)) expect(client.connection.errorReason).to(beIdenticalTo(protocolError.error)) done() } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(channel.errorReason).to(beIdenticalTo(protocolError.error)) } @@ -2453,14 +2453,14 @@ class RealtimeClientConnection: QuickSpec { fail("TestProxyTransport is not set"); return } - channel.once(.Detached) { _ in + channel.once(.detached) { _ in fail("Should not detach channels") } defer { channel.off() } waitUntil(timeout: testTimeout) { done in // Wait for token to expire - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in guard let error = stateChange?.reason else { fail("Error is nil"); done(); return } @@ -2471,7 +2471,7 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in // Wait for connection resume - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -2481,7 +2481,7 @@ class RealtimeClientConnection: QuickSpec { fail("TestProxyTransport is not set"); return } - let connectedMessages = secondTransport.protocolMessagesReceived.filter{ $0.action == .Connected } + let connectedMessages = secondTransport.protocolMessagesReceived.filter{ $0.action == .connected } expect(connectedMessages).to(haveCount(1)) //New transport connected guard let receivedConnectionId = connectedMessages.first?.connectionId else { fail("ConnectionID is nil"); return @@ -2526,7 +2526,7 @@ class RealtimeClientConnection: QuickSpec { var receivedMessages = [String]() waitUntil(timeout: testTimeout) { done in - channel1.subscribeWithAttachCallback({ errorInfo in + channel1.subscribe(attachCallback: { errorInfo in expect(errorInfo).to(beNil()) done() }, callback: { message in @@ -2541,13 +2541,13 @@ class RealtimeClientConnection: QuickSpec { } waitUntil(timeout: testTimeout) { done in - client1.connection.once(.Connecting) { _ in + client1.connection.once(.connecting) { _ in expect(receivedMessages).to(beEmpty()) done() } } - expect(client1.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client1.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) expect(receivedMessages).toEventually(equal(expectedMessages), timeout: testTimeout) } @@ -2560,27 +2560,27 @@ class RealtimeClientConnection: QuickSpec { options.disconnectedRetryTimeout = 1.0 let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) client.onDisconnected() waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connecting) { _ in + client.connection.once(.connecting) { _ in client.connection.setKey("key_to_be_replaced") done() } } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in let transport = client.transport as! TestProxyTransport - let firstConnectionDetails = transport.protocolMessagesReceived.filter{ $0.action == .Connected }[0].connectionDetails + let firstConnectionDetails = transport.protocolMessagesReceived.filter{ $0.action == .connected }[0].connectionDetails expect(firstConnectionDetails!.connectionKey).toNot(beNil()) expect(client.connection.key).to(equal(firstConnectionDetails!.connectionKey)) done() @@ -2600,13 +2600,13 @@ class RealtimeClientConnection: QuickSpec { var resumed = false waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in var sentQueuedMessage: ARTMessage? channel.publish(nil, data: "message") { _ in if resumed { let transport = client.transport as! TestProxyTransport - expect(transport.protocolMessagesReceived.filter{ $0.action == .Ack }).to(haveCount(1)) - let sentTransportMessage = transport.protocolMessagesSent.filter{ $0.action == .Message }.first!.messages![0] + expect(transport.protocolMessagesReceived.filter{ $0.action == .ack }).to(haveCount(1)) + let sentTransportMessage = transport.protocolMessagesSent.filter{ $0.action == .message }.first!.messages![0] expect(sentQueuedMessage).to(beIdenticalTo(sentTransportMessage)) done() } @@ -2617,10 +2617,10 @@ class RealtimeClientConnection: QuickSpec { delay(0) { client.onDisconnected() } - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in resumed = true - channel.testSuite_injectIntoMethodBefore(#selector(channel.sendQueuedMessages)) { - channel.testSuite_getArgumentFrom(#selector(channel.sendMessage(_:callback:)), atIndex: 0) { arg0 in + channel.testSuite_injectIntoMethod(before: #selector(channel.sendQueuedMessages)) { + channel.testSuite_getArgument(from: #selector(channel.send), at: 0) { arg0 in sentQueuedMessage = (arg0 as? ARTProtocolMessage)?.messages?[0] } } @@ -2647,7 +2647,7 @@ class RealtimeClientConnection: QuickSpec { client.simulateLostConnectionAndState() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) expect(channel.errorReason?.message).to(contain("Unable to recover connection")) } @@ -2665,19 +2665,19 @@ class RealtimeClientConnection: QuickSpec { options.token = getTestToken(key: options.key, ttl: tokenTtl) let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) defer { client.dispose() client.close() } client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) weak var firstTransport = client.transport as? TestProxyTransport waitUntil(timeout: testTimeout) { done in // Wait for token to expire - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in guard let error = stateChange?.reason else { fail("Error is nil"); done(); return } @@ -2687,7 +2687,7 @@ class RealtimeClientConnection: QuickSpec { } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -2701,7 +2701,7 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in client.ping { error in expect(error).to(beNil()) - expect((client.transport as! TestProxyTransport).protocolMessagesReceived.filter({ $0.action == .Connected })).to(haveCount(1)) + expect((client.transport as! TestProxyTransport).protocolMessagesReceived.filter({ $0.action == .connected })).to(haveCount(1)) done() } } @@ -2722,19 +2722,19 @@ class RealtimeClientConnection: QuickSpec { } let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) defer { client.dispose() client.close() } client.connect() - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) weak var firstTransport = client.transport as? TestProxyTransport waitUntil(timeout: testTimeout) { done in // Wait for token to expire - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in guard let error = stateChange?.reason else { fail("Error is nil"); done(); return } @@ -2745,7 +2745,7 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in // Renewal will fail - client.connection.once(.Failed) { stateChange in + client.connection.once(.failed) { stateChange in guard let error = stateChange?.reason else { fail("Error is nil"); done(); return } @@ -2755,7 +2755,7 @@ class RealtimeClientConnection: QuickSpec { } } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Failed)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.failed)) } } @@ -2778,7 +2778,7 @@ class RealtimeClientConnection: QuickSpec { let channelReceive = clientReceive.channels.get("test") waitUntil(timeout: testTimeout) { done in - channelReceive.subscribeWithAttachCallback({ error in + channelReceive.subscribe(attachCallback: { error in expect(error).to(beNil()) channelSend.publish(nil, data: "message") { error in expect(error).to(beNil()) @@ -2819,7 +2819,7 @@ class RealtimeClientConnection: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in expect(client.connection.serial).to(equal(-1)) expect(client.connection.recoveryKey).to(equal("\(client.connection.key!):\(client.connection.serial)")) } @@ -2847,7 +2847,7 @@ class RealtimeClientConnection: QuickSpec { let clientOriginal = ARTRealtime(options: options) defer { clientOriginal.close() } - expect(clientOriginal.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(clientOriginal.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let expectedConnectionId = clientOriginal.connection.id @@ -2858,9 +2858,9 @@ class RealtimeClientConnection: QuickSpec { defer { clientRecover.close() } waitUntil(timeout: testTimeout) { done in - clientRecover.connection.once(.Connected) { _ in + clientRecover.connection.once(.connected) { _ in let transport = clientRecover.transport as! TestProxyTransport - let firstConnectionDetails = transport.protocolMessagesReceived.filter{ $0.action == .Connected }.first!.connectionDetails + let firstConnectionDetails = transport.protocolMessagesReceived.filter{ $0.action == .connected }.first!.connectionDetails expect(firstConnectionDetails!.connectionKey).toNot(beNil()) expect(clientRecover.connection.id).to(equal(expectedConnectionId)) expect(clientRecover.connection.key).to(equal(firstConnectionDetails!.connectionKey)) @@ -2880,8 +2880,8 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { _ in - client.connection.once(.Closed) { _ in + client.connection.once(.connected) { _ in + client.connection.once(.closed) { _ in expect(client.connection.recoveryKey).to(beNil()) expect(client.connection.key).to(beNil()) expect(client.connection.id).to(beNil()) @@ -2904,7 +2904,7 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange!.reason!.message).to(contain("Unable to recover connection")) expect(client.connection.errorReason).to(beIdenticalTo(stateChange!.reason)) done() @@ -2943,7 +2943,7 @@ class RealtimeClientConnection: QuickSpec { let client = AblyTests.newRealtime(options) let channel = client.channels.get("test") - TestProxyTransport.network = .HostUnreachable + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -2951,7 +2951,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) } defer { TestProxyTransport.networkConnectEvent = nil } @@ -2975,8 +2975,8 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) let channel = client.channels.get("test") - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .HostUnreachable + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -2984,7 +2984,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) if urlConnections.count == 1 { TestProxyTransport.network = nil } @@ -3015,8 +3015,8 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) let channel = client.channels.get("test") - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .HostUnreachable + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -3024,7 +3024,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) if urlConnections.count == 1 { TestProxyTransport.network = nil } @@ -3049,16 +3049,16 @@ class RealtimeClientConnection: QuickSpec { // RTN17d context("should use an alternative host when") { - for caseTest: NetworkAnswer in [.HostUnreachable, - .RequestTimeout(timeout: 0.1), - .HostInternalError(code: 501)] { + for caseTest: NetworkAnswer in [.hostUnreachable, + .requestTimeout(timeout: 0.1), + .hostInternalError(code: 501)] { it("\(caseTest)") { let options = ARTClientOptions(key: "xxxx:xxxx") options.autoConnect = false let client = ARTRealtime(options: options) let channel = client.channels.get("test") - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) TestProxyTransport.network = caseTest defer { TestProxyTransport.network = nil } @@ -3067,7 +3067,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) if urlConnections.count == 1 { TestProxyTransport.network = nil } @@ -3097,9 +3097,9 @@ class RealtimeClientConnection: QuickSpec { client.dispose() client.close() } - client.setTransportClass(TestProxyTransport.self) + client.setTransport(TestProxyTransport.self) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) guard let wsTransport = client.transport as? ARTWebSocketTransport else { fail("expected WS transport") @@ -3108,7 +3108,7 @@ class RealtimeClientConnection: QuickSpec { wsTransport.webSocket(wsTransport.websocket, didFailWithError:NSError(domain: "NSPOSIXErrorDomain", code: 57, userInfo: [NSLocalizedDescriptionKey: "Socket is not connected"])) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Disconnected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.disconnected), timeout: testTimeout) } it("should not use an alternative host when the client receives a bad request") { @@ -3117,8 +3117,8 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) let channel = client.channels.get("test") - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .Host400BadRequest + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .host400BadRequest defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -3126,7 +3126,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) } defer { TestProxyTransport.networkConnectEvent = nil } @@ -3150,8 +3150,8 @@ class RealtimeClientConnection: QuickSpec { let client = ARTRealtime(options: options) let channel = client.channels.get("test") - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .HostUnreachable + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -3159,7 +3159,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) TestProxyTransport.network = nil } defer { TestProxyTransport.networkConnectEvent = nil } @@ -3197,8 +3197,8 @@ class RealtimeClientConnection: QuickSpec { let testHttpExecutor = TestProxyHTTPExecutor() client.rest.httpExecutor = testHttpExecutor - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .HostUnreachable + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -3206,7 +3206,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) } defer { TestProxyTransport.networkConnectEvent = nil } @@ -3219,7 +3219,7 @@ class RealtimeClientConnection: QuickSpec { } } - expect(NSRegularExpression.match(testHttpExecutor.requests[0].URL!.absoluteString, pattern: "//internet-up.ably-realtime.com/is-the-internet-up.txt")).to(beTrue()) + expect(NSRegularExpression.match(testHttpExecutor.requests[0].url!.absoluteString, pattern: "//internet-up.ably-realtime.com/is-the-internet-up.txt")).to(beTrue()) expect(urlConnections).to(haveCount(6)) // default + 5 fallbacks let extractHostname = { (url: NSURL) in @@ -3243,8 +3243,8 @@ class RealtimeClientConnection: QuickSpec { let testHttpExecutor = TestProxyHTTPExecutor() client.rest.httpExecutor = testHttpExecutor - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .HostUnreachable + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -3252,7 +3252,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) } defer { TestProxyTransport.networkConnectEvent = nil } @@ -3265,7 +3265,7 @@ class RealtimeClientConnection: QuickSpec { } } - expect(NSRegularExpression.match(testHttpExecutor.requests[0].URL!.absoluteString, pattern: "//internet-up.ably-realtime.com/is-the-internet-up.txt")).to(beTrue()) + expect(NSRegularExpression.match(testHttpExecutor.requests[0].url!.absoluteString, pattern: "//internet-up.ably-realtime.com/is-the-internet-up.txt")).to(beTrue()) expect(urlConnections).to(haveCount(6)) // default + 5 provided fallbacks let extractHostname = { (url: NSURL) in @@ -3287,8 +3287,8 @@ class RealtimeClientConnection: QuickSpec { let testHttpExecutor = TestProxyHTTPExecutor() client.rest.httpExecutor = testHttpExecutor - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .HostUnreachable + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -3296,7 +3296,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) } defer { TestProxyTransport.networkConnectEvent = nil } @@ -3309,7 +3309,7 @@ class RealtimeClientConnection: QuickSpec { } } - expect(NSRegularExpression.match(testHttpExecutor.requests[0].URL!.absoluteString, pattern: "//internet-up.ably-realtime.com/is-the-internet-up.txt")).to(beTrue()) + expect(NSRegularExpression.match(testHttpExecutor.requests[0].url!.absoluteString, pattern: "//internet-up.ably-realtime.com/is-the-internet-up.txt")).to(beTrue()) expect(urlConnections).to(haveCount(1)) } @@ -3322,8 +3322,8 @@ class RealtimeClientConnection: QuickSpec { let testHttpExecutor = TestProxyHTTPExecutor() client.rest.httpExecutor = testHttpExecutor - client.setTransportClass(TestProxyTransport.self) - TestProxyTransport.network = .HostUnreachable + client.setTransport(TestProxyTransport.self) + TestProxyTransport.network = .hostUnreachable defer { TestProxyTransport.network = nil } var urlConnections = [NSURL]() @@ -3331,7 +3331,7 @@ class RealtimeClientConnection: QuickSpec { if client.transport !== transport { return } - urlConnections.append(url) + urlConnections.append(url as NSURL) if urlConnections.count == 2 { TestProxyTransport.network = nil (client.transport as! TestProxyTransport).simulateTransportSuccess() @@ -3350,7 +3350,7 @@ class RealtimeClientConnection: QuickSpec { client.time { _ in } - let timeRequestUrl = testHttpExecutor.requests.last!.URL! + let timeRequestUrl = testHttpExecutor.requests.last!.url! expect(timeRequestUrl.host).to(equal(urlConnections[1].host)) } @@ -3364,22 +3364,22 @@ class RealtimeClientConnection: QuickSpec { defer { realtime.close() } waitUntil(timeout: testTimeout) { done in - realtime.connection.once(.Connecting) { stateChange in + realtime.connection.once(.connecting) { stateChange in expect(stateChange!.reason).to(beNil()) let transport = realtime.transport as! TestProxyTransport transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Connected { + if protocolMessage.action == .connected { protocolMessage.connectionDetails!.clientId = "john" protocolMessage.connectionDetails!.connectionKey = "123" } } } - realtime.connection.once(.Connected) { stateChange in + realtime.connection.once(.connected) { stateChange in expect(stateChange!.reason).to(beNil()) let transport = realtime.transport as! TestProxyTransport - let connectedProtocolMessage = transport.protocolMessagesReceived.filter{ $0.action == .Connected }[0] + let connectedProtocolMessage = transport.protocolMessagesReceived.filter{ $0.action == .connected }[0] expect(realtime.auth.clientId).to(equal(connectedProtocolMessage.connectionDetails!.clientId)) expect(realtime.connection.key).to(equal(connectedProtocolMessage.connectionDetails!.connectionKey)) @@ -3411,11 +3411,11 @@ class RealtimeClientConnection: QuickSpec { fail("Transport is nil"); done(); return } expect(newTransport).toNot(beIdenticalTo(transport)) - expect(transport.protocolMessagesSent.filter{ $0.action == .Message }).to(haveCount(1)) - expect(transport.protocolMessagesReceived.filter{ $0.action == .Connected }).to(haveCount(1)) - expect(newTransport.protocolMessagesReceived.filter{ $0.action == .Connected }).to(haveCount(1)) - expect(transport.protocolMessagesReceived.filter{ $0.action == .Connected }).to(haveCount(1)) - expect(newTransport.protocolMessagesSent.filter{ $0.action == .Message }).to(haveCount(1)) + expect(transport.protocolMessagesSent.filter{ $0.action == .message }).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter{ $0.action == .connected }).to(haveCount(1)) + expect(newTransport.protocolMessagesReceived.filter{ $0.action == .connected }).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter{ $0.action == .connected }).to(haveCount(1)) + expect(newTransport.protocolMessagesSent.filter{ $0.action == .message }).to(haveCount(1)) done() } client.onDisconnected() @@ -3431,7 +3431,7 @@ class RealtimeClientConnection: QuickSpec { let channel = client.channels.get("test") let transport = client.transport as! TestProxyTransport - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in transport.ignoreSends = true @@ -3440,14 +3440,14 @@ class RealtimeClientConnection: QuickSpec { guard let newTransport = client.transport as? TestProxyTransport else { fail("Transport is nil"); done(); return } - expect(transport.protocolMessagesReceived.filter{ $0.action == .Connected }).to(haveCount(1)) - expect(newTransport.protocolMessagesReceived.filter{ $0.action == .Connected }).to(haveCount(1)) - expect(transport.protocolMessagesSent.filter{ $0.action == .Attach }).to(haveCount(0)) - expect(transport.protocolMessagesSentIgnored.filter{ $0.action == .Attach }).to(haveCount(1)) - expect(newTransport.protocolMessagesSent.filter{ $0.action == .Attach }).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter{ $0.action == .connected }).to(haveCount(1)) + expect(newTransport.protocolMessagesReceived.filter{ $0.action == .connected }).to(haveCount(1)) + expect(transport.protocolMessagesSent.filter{ $0.action == .attach }).to(haveCount(0)) + expect(transport.protocolMessagesSentIgnored.filter{ $0.action == .attach }).to(haveCount(1)) + expect(newTransport.protocolMessagesSent.filter{ $0.action == .attach }).to(haveCount(1)) done() } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) transport.ignoreSends = false client.onDisconnected() } @@ -3462,7 +3462,7 @@ class RealtimeClientConnection: QuickSpec { let channel = client.channels.get("test") let transport = client.transport as! TestProxyTransport - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.attach() { _ in done() } @@ -3475,14 +3475,14 @@ class RealtimeClientConnection: QuickSpec { guard let newTransport = client.transport as? TestProxyTransport else { fail("Transport is nil"); done(); return } - expect(transport.protocolMessagesReceived.filter{ $0.action == .Connected }).to(haveCount(1)) - expect(newTransport.protocolMessagesReceived.filter{ $0.action == .Connected }).to(haveCount(1)) - expect(transport.protocolMessagesSent.filter{ $0.action == .Detach }).to(haveCount(0)) - expect(transport.protocolMessagesSentIgnored.filter{ $0.action == .Detach }).to(haveCount(1)) - expect(newTransport.protocolMessagesSent.filter{ $0.action == .Detach }).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter{ $0.action == .connected }).to(haveCount(1)) + expect(newTransport.protocolMessagesReceived.filter{ $0.action == .connected }).to(haveCount(1)) + expect(transport.protocolMessagesSent.filter{ $0.action == .detach }).to(haveCount(0)) + expect(transport.protocolMessagesSentIgnored.filter{ $0.action == .detach }).to(haveCount(1)) + expect(newTransport.protocolMessagesSent.filter{ $0.action == .detach }).to(haveCount(1)) done() } - expect(channel.state).to(equal(ARTRealtimeChannelState.Detaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detaching)) transport.ignoreSends = false client.onDisconnected() } @@ -3513,15 +3513,15 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in client.connection.on { stateChange in switch stateChange!.current { - case .Connecting: + case .connecting: expect(stateChange!.reason).to(beNil()) guard let reachability = client.reachability as? TestReachability else { fail("expected test reachability") done(); return } expect(reachability.host).to(equal(client.options.realtimeHost)) - reachability.simulate(reachable: false) - case .Disconnected: + reachability.simulate(false) + case .disconnected: guard let reason = stateChange!.reason else { fail("expected error reason") done(); return @@ -3540,15 +3540,15 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in client.connection.on { stateChange in switch stateChange!.current { - case .Connected: + case .connected: expect(stateChange!.reason).to(beNil()) guard let reachability = client.reachability as? TestReachability else { fail("expected test reachability") done(); return } expect(reachability.host).to(equal(client.options.realtimeHost)) - reachability.simulate(reachable: false) - case .Disconnected: + reachability.simulate(false) + case .disconnected: guard let reason = stateChange!.reason else { fail("expected error reason") done(); return @@ -3579,21 +3579,21 @@ class RealtimeClientConnection: QuickSpec { waitUntil(timeout: testTimeout) { done in client.connection.on { stateChange in switch stateChange!.current { - case .Connecting: - if stateChange!.previous == .Disconnected { + case .connecting: + if stateChange!.previous == .disconnected { client.onSuspended() - } else if stateChange!.previous == .Suspended { + } else if stateChange!.previous == .suspended { done() } - case .Connected: + case .connected: client.onDisconnected() - case .Disconnected, .Suspended: + case .disconnected, .suspended: guard let reachability = client.reachability as? TestReachability else { fail("expected test reachability") done(); return } expect(reachability.host).to(equal(client.options.realtimeHost)) - reachability.simulate(reachable: true) + reachability.simulate(true) default: break } @@ -3626,14 +3626,14 @@ class RealtimeClientConnection: QuickSpec { } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Update) { stateChange in + client.connection.once(.update) { stateChange in expect(stateChange?.reason).to(beNil()) expect(initialToken).toNot(equal(client.auth.tokenDetails?.token)) done() } let authMessage = ARTProtocolMessage() - authMessage.action = .Auth + authMessage.action = .auth client.transport?.receive(authMessage) } @@ -3682,18 +3682,18 @@ class RealtimeClientConnection: QuickSpec { fail("Initial token is nil"); return } - channel.once(.Detached) { _ in + channel.once(.detached) { _ in fail("Should not detach channels") } var authorizeMethodCallCount = 0 - let hook = client.auth.testSuite_injectIntoMethodAfter(#selector(client.auth.authorize(_:options:callback:))) { + let hook = client.auth.testSuite_injectIntoMethod(after: #selector(client.auth.authorize(_:options:callback:))) { authorizeMethodCallCount += 1 } defer { hook.remove() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in guard let error = stateChange?.reason else { fail("Error is nil"); done(); return } @@ -3703,7 +3703,7 @@ class RealtimeClientConnection: QuickSpec { } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) expect(initialToken).toNot(equal(client.auth.tokenDetails?.token)) done() @@ -3739,13 +3739,13 @@ class RealtimeClientConnection: QuickSpec { it("the client may receive a CONNECTED ProtocolMessage from Ably at any point and should emit an UPDATE event") { let options = AblyTests.commonAppSetup() options.authCallback = { _, completion in - completion(getTestToken(key: options.key!, ttl: 35), nil) + completion(getTestToken(key: options.key!, ttl: 35) as NSString, nil) } let client = ARTRealtime(options: options) defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -3754,21 +3754,21 @@ class RealtimeClientConnection: QuickSpec { expect(client.auth.clientId).to(beNil()) client.options.authCallback = { _, completion in - completion(getTestToken(key: options.key!, ttl: 5, clientId: "tester"), nil) + completion(getTestToken(key: options.key!, clientId: "tester", ttl: 5) as NSString, nil) } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in fail("Should not emit a Connected state") } waitUntil(timeout: 40) { done in - client.connection.once(.Update) { stateChange in + client.connection.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } expect(stateChange.reason).to(beNil()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) - expect(stateChange.current).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) + expect(stateChange.current).to(equal(ARTRealtimeConnectionState.connected)) expect(stateChange.current).to(equal(stateChange.previous)) done() } @@ -3785,7 +3785,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -3794,16 +3794,16 @@ class RealtimeClientConnection: QuickSpec { guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } - guard let originalConnectedMessage = transport.protocolMessagesReceived.filter({ $0.action == .Connected }).first else { + guard let originalConnectedMessage = transport.protocolMessagesReceived.filter({ $0.action == .connected }).first else { fail("First CONNECTED message not received"); return } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in fail("Should not emit a Connected state") } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Update) { stateChange in + client.connection.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ConnectionStateChange is nil"); done(); return } @@ -3811,14 +3811,14 @@ class RealtimeClientConnection: QuickSpec { fail("Reason error is nil"); done(); return } expect(error.code) == 1234 - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) - expect(stateChange.current).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) + expect(stateChange.current).to(equal(ARTRealtimeConnectionState.connected)) expect(stateChange.current).to(equal(stateChange.previous)) done() } let connectedMessageWithError = originalConnectedMessage - connectedMessageWithError.error = ARTErrorInfo.createWithCode(1234, message: "fabricated error") + connectedMessageWithError.error = ARTErrorInfo.create(withCode: 1234, message: "fabricated error") client.transport?.receive(connectedMessageWithError) } @@ -3834,24 +3834,24 @@ class RealtimeClientConnection: QuickSpec { client.close() } - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) let protoMsg = ARTProtocolMessage() - protoMsg.action = .Disconnect - protoMsg.error = ARTErrorInfo.createWithCode(123, message: "test error") + protoMsg.action = .disconnect + protoMsg.error = ARTErrorInfo.create(withCode: 123, message: "test error") client.transport?.receive(protoMsg) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Disconnected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.disconnected)) expect(client.connection.errorReason).to(equal(protoMsg.error)) } context("with fixture messages") { - let fixtures = JSON(data: NSData(contentsOfFile: pathForTestResource(testResourcesPath + "messages-encoding.json"))!, options: .MutableContainers) + let fixtures = JSON(data: NSData(contentsOfFile: pathForTestResource(testResourcesPath + "messages-encoding.json"))! as Data, options: .mutableContainers) - func expectDataToMatch(message: ARTMessage, _ fixtureMessage: JSON) { + func expectDataToMatch(_ message: ARTMessage, _ fixtureMessage: JSON) { switch fixtureMessage["expectedType"].string! { case "string": - expect(message.data as? NSString).to(equal(fixtureMessage["expectedValue"].string!)) + expect(message.data as? NSString).to(equal(fixtureMessage["expectedValue"].string! as NSString?)) case "jsonObject": if let data = message.data as? NSDictionary { expect(JSON(data)).to(equal(fixtureMessage["expectedValue"])) @@ -3865,7 +3865,7 @@ class RealtimeClientConnection: QuickSpec { fail("expected NSArray") } case "binary": - expect(message.data as? NSData).to(equal(fixtureMessage["expectedHexValue"].string!.dataFromHexadecimalString()!)) + expect(message.data as? NSData).to(equal(fixtureMessage["expectedHexValue"].string!.dataFromHexadecimalString()! as NSData?)) default: fail("unhandled: \(fixtureMessage["expectedType"].string!)") } @@ -3879,8 +3879,8 @@ class RealtimeClientConnection: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) - if channel.state != .Attached { + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) + if channel.state != .attached { return } @@ -3894,14 +3894,14 @@ class RealtimeClientConnection: QuickSpec { done() } - let request = NSMutableURLRequest(URL: NSURL(string: "/channels/\(channel.name)/messages")!) - request.HTTPMethod = "POST" - request.HTTPBody = try! fixtureMessage.rawData() + let request = NSMutableURLRequest(url: NSURL(string: "/channels/\(channel.name)/messages")! as URL) + request.httpMethod = "POST" + request.httpBody = try! fixtureMessage.rawData() request.allHTTPHeaderFields = [ "Accept" : "application/json", "Content-Type" : "application/json" ] - client.rest.executeRequest(request, withAuthOption: .On, completion: { _, _, err in + client.rest.execute(request as URLRequest, withAuthOption: .on, completion: { _, _, err in if let err = err { fail("\(err)") } @@ -3922,10 +3922,10 @@ class RealtimeClientConnection: QuickSpec { return } - let request = NSMutableURLRequest(URL: NSURL(string: "/channels/\(channel.name)/messages?limit=1")!) - request.HTTPMethod = "GET" + let request = NSMutableURLRequest(url: NSURL(string: "/channels/\(channel.name)/messages?limit=1")! as URL) + request.httpMethod = "GET" request.allHTTPHeaderFields = ["Accept" : "application/json"] - client.rest.executeRequest(request, withAuthOption: .On, completion: { _, data, err in + client.rest.execute(request as URLRequest, withAuthOption: .on, completion: { _, data, err in if let err = err { fail("\(err)") done() @@ -3980,14 +3980,14 @@ class RealtimeClientConnection: QuickSpec { partlyDone() } - let request = NSMutableURLRequest(URL: NSURL(string: "/channels/\(realtimeSubscribeChannelMsgPack.name)/messages")!) - request.HTTPMethod = "POST" - request.HTTPBody = try! fixtureMessage.rawData() + let request = NSMutableURLRequest(url: NSURL(string: "/channels/\(realtimeSubscribeChannelMsgPack.name)/messages")! as URL) + request.httpMethod = "POST" + request.httpBody = try! fixtureMessage.rawData() request.allHTTPHeaderFields = [ "Accept" : "application/json", "Content-Type" : "application/json" ] - restPublishClient.executeRequest(request, withAuthOption: .On, completion: { _, _, err in + restPublishClient.execute(request as URLRequest, withAuthOption: .on, completion: { _, _, err in if let err = err { fail("\(err)") } @@ -4007,9 +4007,9 @@ class RealtimeClientConnection: QuickSpec { for (_, fixtureMessage) in fixtures["messages"] { var data: AnyObject if fixtureMessage["expectedType"] == "binary" { - data = fixtureMessage["expectedHexValue"].string!.dataFromHexadecimalString()! + data = fixtureMessage["expectedHexValue"].string!.dataFromHexadecimalString()! as AnyObject } else { - data = fixtureMessage["expectedValue"].object + data = fixtureMessage["expectedValue"].object as AnyObject } for restPublishChannel in [restPublishChannelMsgPack, restPublishChannelJSON] { @@ -4025,10 +4025,10 @@ class RealtimeClientConnection: QuickSpec { } waitUntil(timeout: testTimeout) { done in - let request = NSMutableURLRequest(URL: NSURL(string: "/channels/\(restPublishChannel.name)/messages?limit=1")!) - request.HTTPMethod = "GET" + let request = NSMutableURLRequest(url: NSURL(string: "/channels/\(restPublishChannel.name)/messages?limit=1")! as URL) + request.httpMethod = "GET" request.allHTTPHeaderFields = ["Accept" : "application/json"] - restRetrieveClient.executeRequest(request, withAuthOption: .On, completion: { _, data, err in + restRetrieveClient.execute(request as URLRequest, withAuthOption: .on, completion: { _, data, err in if let err = err { fail("\(err)") done() @@ -4051,7 +4051,7 @@ class RealtimeClientConnection: QuickSpec { defer { client.dispose(); client.close() } waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -4065,25 +4065,25 @@ class RealtimeClientConnection: QuickSpec { } // Let the token expire delay(0.1) { - completion(tokenDetails.token, nil) + completion(tokenDetails.token as ARTTokenDetailsCompatible?, nil) } } } let authMessage = ARTProtocolMessage() - authMessage.action = .Auth + authMessage.action = .auth client.transport?.receive(authMessage) client.close() waitUntil(timeout: testTimeout) { done in - client.connection.once(.Failed) { _ in + client.connection.once(.failed) { _ in fail("Should not receive error 40142") } - client.connection.once(.Connected) { _ in + client.connection.once(.connected) { _ in fail("Should not connect") } - client.connection.once(.Closed) { _ in + client.connection.once(.closed) { _ in done() } } diff --git a/Spec/RealtimeClientPresence.swift b/Spec/RealtimeClientPresence.swift index 662b55d6d..f25e53ecf 100644 --- a/Spec/RealtimeClientPresence.swift +++ b/Spec/RealtimeClientPresence.swift @@ -28,20 +28,20 @@ class RealtimeClientPresence: QuickSpec { let options = AblyTests.commonAppSetup() options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) let transport = client.transport as! TestProxyTransport - let attached = transport.protocolMessagesReceived.filter({ $0.action == .Attached })[0] + let attached = transport.protocolMessagesReceived.filter({ $0.action == .attached })[0] expect(attached.flags & 0x1).to(equal(0)) expect(attached.hasPresence).to(beFalse()) - expect(channel.presence.syncComplete).to(beFalse()) + expect(channel.presence.getSyncComplete).to(beFalse()) expect(channel.presenceMap.syncComplete).to(beFalse()) } @@ -64,25 +64,25 @@ class RealtimeClientPresence: QuickSpec { options.autoConnect = false let client = ARTRealtime(options: options) - client.setTransportClass(TestProxyTransport) + client.setTransport(TestProxyTransport.self) client.connect() defer { client.dispose(); client.close() } let channel = client.channels.get("test") channel.attach() - expect(channel.presence.syncComplete).to(beFalse()) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.presence.getSyncComplete).to(beFalse()) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) let transport = client.transport as! TestProxyTransport - let attached = transport.protocolMessagesReceived.filter({ $0.action == .Attached })[0] + let attached = transport.protocolMessagesReceived.filter({ $0.action == .attached })[0] // There are members present on the channel expect(attached.flags & 0x1).to(equal(1)) expect(attached.hasPresence).to(beTrue()) - expect(channel.presence.syncComplete).toEventually(beTrue(), timeout: testTimeout) + expect(channel.presence.getSyncComplete).toEventually(beTrue(), timeout: testTimeout) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Sync })).to(haveCount(3)) + expect(transport.protocolMessagesReceived.filter({ $0.action == .sync })).to(haveCount(3)) } } @@ -111,7 +111,7 @@ class RealtimeClientPresence: QuickSpec { fail("TestProxyTransport is not set"); return } transport.afterProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Sync { + if protocolMessage.action == .sync { lastSyncSerial = protocolMessage.channelSerial client.onDisconnected() done() @@ -121,21 +121,21 @@ class RealtimeClientPresence: QuickSpec { } expect(channel.presenceMap.members).toNot(haveCount(150)) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connecting), timeout: options.disconnectedRetryTimeout + 1.0) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connecting), timeout: options.disconnectedRetryTimeout + 1.0) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) // Client library requests a SYNC resume by sending a SYNC ProtocolMessage with the last received sync serial number guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } - let syncSentProtocolMessages = transport.protocolMessagesSent.filter({ $0.action == .Sync }) - guard let syncSentMessage = syncSentProtocolMessages.last where syncSentProtocolMessages.count == 1 else { + let syncSentProtocolMessages = transport.protocolMessagesSent.filter({ $0.action == .sync }) + guard let syncSentMessage = syncSentProtocolMessages.last, syncSentProtocolMessages.count == 1 else { fail("Should send one SYNC protocol message"); return } expect(syncSentMessage.channelSerial).to(equal(lastSyncSerial)) - expect(transport.protocolMessagesReceived.filter{ $0.action == .Sync }).toEventually(haveCount(2), timeout: testTimeout) + expect(transport.protocolMessagesReceived.filter{ $0.action == .sync }).toEventually(haveCount(2), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.presence.get { members, error in @@ -174,8 +174,8 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.presence.subscribe(.Present) { error in - expect(channel.presence.syncComplete).to(beFalse()) + channel.presence.subscribe(.present) { error in + expect(channel.presence.getSyncComplete).to(beFalse()) partialDone() } @@ -185,35 +185,35 @@ class RealtimeClientPresence: QuickSpec { // Inject a SYNC Presence message (first page) let sync1Message = ARTProtocolMessage() - sync1Message.action = .Sync + sync1Message.action = .sync sync1Message.channel = channel.name sync1Message.channelSerial = "sequenceid:cursor" sync1Message.connectionSerial = lastConnectionSerial + 1 - sync1Message.timestamp = NSDate() + sync1Message.timestamp = NSDate() as Date sync1Message.presence = [ - ARTPresenceMessage(clientId: "a", action: .Present, connectionId: "another", id: "another:0:0"), - ARTPresenceMessage(clientId: "b", action: .Present, connectionId: "another", id: "another:0:1"), + ARTPresenceMessage(clientId: "a", action: .present, connectionId: "another", id: "another:0:0"), + ARTPresenceMessage(clientId: "b", action: .present, connectionId: "another", id: "another:0:1"), ] transport.receive(sync1Message) // Inject a SYNC Presence message (last page) let sync2Message = ARTProtocolMessage() - sync2Message.action = .Sync + sync2Message.action = .sync sync2Message.channel = channel.name sync2Message.channelSerial = "sequenceid:" //indicates SYNC is complete sync2Message.connectionSerial = lastConnectionSerial + 2 - sync2Message.timestamp = NSDate() + sync2Message.timestamp = NSDate() as Date sync2Message.presence = [ - ARTPresenceMessage(clientId: "a", action: .Leave, connectionId: "another", id: "another:1:0"), + ARTPresenceMessage(clientId: "a", action: .leave, connectionId: "another", id: "another:1:0"), ] transport.receive(sync2Message) } - expect(channel.presence.syncComplete).to(beTrue()) + expect(channel.presence.getSyncComplete).to(beTrue()) waitUntil(timeout: testTimeout) { done in channel.presence.get { members, error in expect(error).to(beNil()) - guard let members = members where members.count == 1 else { + guard let members = members, members.count == 1 else { fail("Should at least have 1 member"); done(); return } expect(members[0].clientId).to(equal("b")) @@ -244,8 +244,8 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.presence.subscribe(.Present) { error in - expect(channel.presence.syncComplete).to(beFalse()) + channel.presence.subscribe(.present) { error in + expect(channel.presence.getSyncComplete).to(beFalse()) partialDone() } @@ -255,23 +255,23 @@ class RealtimeClientPresence: QuickSpec { // Inject a SYNC Presence message (entirely contained) let syncMessage = ARTProtocolMessage() - syncMessage.action = .Sync + syncMessage.action = .sync syncMessage.channel = channel.name syncMessage.connectionSerial = lastConnectionSerial + 1 - syncMessage.timestamp = NSDate() + syncMessage.timestamp = NSDate() as Date syncMessage.presence = [ - ARTPresenceMessage(clientId: "a", action: .Present, connectionId: "another", id: "another:0:0"), - ARTPresenceMessage(clientId: "b", action: .Present, connectionId: "another", id: "another:0:1"), - ARTPresenceMessage(clientId: "a", action: .Leave, connectionId: "another", id: "another:1:0"), + ARTPresenceMessage(clientId: "a", action: .present, connectionId: "another", id: "another:0:0"), + ARTPresenceMessage(clientId: "b", action: .present, connectionId: "another", id: "another:0:1"), + ARTPresenceMessage(clientId: "a", action: .leave, connectionId: "another", id: "another:1:0"), ] transport.receive(syncMessage) } - expect(channel.presence.syncComplete).to(beTrue()) + expect(channel.presence.getSyncComplete).to(beTrue()) waitUntil(timeout: testTimeout) { done in channel.presence.get { members, error in expect(error).to(beNil()) - guard let members = members where members.count == 1 else { + guard let members = members, members.count == 1 else { fail("Should at least have 1 member"); done(); return } expect(members[0].clientId).to(equal("b")) @@ -309,7 +309,7 @@ class RealtimeClientPresence: QuickSpec { expect(channel.presenceMap.members).to(haveCount(2)) // Inject a local member - let localMember = ARTPresenceMessage(clientId: NSUUID().UUIDString, action: .Enter, connectionId: "another", id: "another:0:0") + let localMember = ARTPresenceMessage(clientId: NSUUID().uuidString, action: .enter, connectionId: "another", id: "another:0:0") channel.presenceMap.add(localMember) expect(channel.presenceMap.members).to(haveCount(3)) expect(channel.presenceMap.members.filter{ clientId, _ in clientId == localMember.clientId }).to(haveCount(1)) @@ -317,7 +317,7 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.presence.get { members, error in expect(error).to(beNil()) - guard let members = members where members.count == 3 else { + guard let members = members, members.count == 3 else { fail("Should at least have 3 members"); done(); return } expect(members.filter{ $0.clientId == localMember.clientId }).to(haveCount(1)) @@ -326,15 +326,15 @@ class RealtimeClientPresence: QuickSpec { } waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Leave) { leave in - expect(channel.presence.syncComplete).to(beFalse()) + channel.presence.subscribe(.leave) { leave in + expect(channel.presence.getSyncComplete).to(beFalse()) expect(leave.clientId).to(equal(localMember.clientId)) done() } // Request a sync let syncMessage = ARTProtocolMessage() - syncMessage.action = .Sync + syncMessage.action = .sync syncMessage.channel = channel.name guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); done(); return @@ -345,7 +345,7 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.presence.get { members, error in expect(error).to(beNil()) - guard let members = members where members.count == 2 else { + guard let members = members, members.count == 2 else { fail("Should at least have 2 members"); done(); return } expect(members.filter{ $0.clientId == localMember.clientId }).to(beEmpty()) @@ -362,8 +362,8 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("foo") // Inject local members - channel.presenceMap.add(ARTPresenceMessage(clientId: "tester1", action: .Enter, connectionId: "another", id: "another:0:0")) - channel.presenceMap.add(ARTPresenceMessage(clientId: "tester2", action: .Enter, connectionId: "another", id: "another:0:1")) + channel.presenceMap.add(ARTPresenceMessage(clientId: "tester1", action: .enter, connectionId: "another", id: "another:0:0")) + channel.presenceMap.add(ARTPresenceMessage(clientId: "tester2", action: .enter, connectionId: "another", id: "another:0:1")) guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return @@ -372,14 +372,14 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(4, done: done) transport.afterProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Attached { + if protocolMessage.action == .attached { expect(protocolMessage.hasPresence).to(beFalse()) partialDone() } } - channel.presence.subscribe(.Leave) { leave in + channel.presence.subscribe(.leave) { leave in expect(leave.clientId?.hasPrefix("tester")).to(beTrue()) - expect(leave.action).to(equal(ARTPresenceAction.Leave)) + expect(leave.action).to(equal(ARTPresenceAction.leave)) expect(leave.timestamp).to(beCloseTo(NSDate(), within: 0.5)) expect(leave.id).to(beNil()) partialDone() //2 times @@ -420,7 +420,7 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in var pending = 250 channel.presence.subscribe { member in - expect(member.action).to(equal(ARTPresenceAction.Present)) + expect(member.action).to(equal(ARTPresenceAction.present)) pending -= 1 if pending == 0 { done() @@ -472,16 +472,16 @@ class RealtimeClientPresence: QuickSpec { return } - expect(receivedMembers[0].action).to(equal(ARTPresenceAction.Enter)) - expect(receivedMembers[0].data as? NSObject).to(equal("online")) + expect(receivedMembers[0].action).to(equal(ARTPresenceAction.enter)) + expect(receivedMembers[0].data as? NSObject).to(equal("online" as NSObject?)) expect(receivedMembers[0].clientId).to(equal("john")) - expect(receivedMembers[1].action).to(equal(ARTPresenceAction.Update)) - expect(receivedMembers[1].data as? NSObject).to(equal("away")) + expect(receivedMembers[1].action).to(equal(ARTPresenceAction.update)) + expect(receivedMembers[1].data as? NSObject).to(equal("away" as NSObject?)) expect(receivedMembers[1].clientId).to(equal("john")) - expect(receivedMembers[2].action).to(equal(ARTPresenceAction.Leave)) - expect(receivedMembers[2].data as? NSObject).to(equal("away")) + expect(receivedMembers[2].action).to(equal(ARTPresenceAction.leave)) + expect(receivedMembers[2].data as? NSObject).to(equal("away" as NSObject?)) expect(receivedMembers[2].clientId).to(equal("john")) } @@ -547,7 +547,7 @@ class RealtimeClientPresence: QuickSpec { defer { channel.off() } waitUntil(timeout: testTimeout) { done in - channel.once(.Failed) { _ in + channel.once(.failed) { _ in expect(channel.presenceMap.members).to(beEmpty()) expect(channel.presenceMap.localMembers).to(beEmpty()) done() @@ -567,7 +567,7 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel.once(.Attaching) { _ in + channel.once(.attaching) { _ in channel.detach() } channel.presence.enterClient("user", data: nil) { error in @@ -599,7 +599,7 @@ class RealtimeClientPresence: QuickSpec { defer { channel.off() } waitUntil(timeout: testTimeout) { done in - channel.once(.Detached) { _ in + channel.once(.detached) { _ in expect(channel.presenceMap.members).to(beEmpty()) expect(channel.presenceMap.localMembers).to(beEmpty()) done() @@ -633,11 +633,11 @@ class RealtimeClientPresence: QuickSpec { channel2.presence.enterClient("Client 2", data: nil) { error in expect(error).to(beNil()) expect(channel2.queuedMessages).to(haveCount(0)) - expect(channel2.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel2.state).to(equal(ARTRealtimeChannelState.attached)) partialDone() } - channel2.presence.subscribe(.Enter) { _ in - if channel2.presence.syncComplete { + channel2.presence.subscribe(.enter) { _ in + if channel2.presence.getSyncComplete { expect(channel2.presenceMap.members).to(haveCount(2)) } else { @@ -648,7 +648,7 @@ class RealtimeClientPresence: QuickSpec { } expect(channel2.queuedMessages).to(haveCount(1)) - expect(channel2.presence.syncComplete).to(beFalse()) + expect(channel2.presence.getSyncComplete).to(beFalse()) expect(channel2.presenceMap.members).to(haveCount(0)) } @@ -656,9 +656,9 @@ class RealtimeClientPresence: QuickSpec { fail("Transport should be a test proxy"); return } - expect(transport.protocolMessagesReceived.filter{ $0.action == .Sync }).to(haveCount(1)) + expect(transport.protocolMessagesReceived.filter{ $0.action == .sync }).to(haveCount(1)) - expect(channel2.presence.syncComplete).toEventually(beTrue(), timeout: testTimeout) + expect(channel2.presence.getSyncComplete).toEventually(beTrue(), timeout: testTimeout) expect(channel2.presenceMap.members).to(haveCount(2)) } @@ -695,31 +695,31 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - client.connection.once(.Disconnected) { stateChange in + client.connection.once(.disconnected) { stateChange in // Token expired partialDone() } - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in guard let transport = client.transport as? TestProxyTransport else { fail("TestProxyTransport is not set"); return } // TODO: use sandbox to reproduce this let attached = ARTProtocolMessage() - attached.action = .Attached + attached.action = .attached attached.channel = channel.name - attached.flags = Int64(ARTProtocolMessageFlag.Resumed.rawValue) + attached.flags = Int64(ARTProtocolMessageFlag.resumed.rawValue) client.transport?.receive(attached) partialDone() } - channel.once(.Update) { stateChange in + channel.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ChannelStageChange is nil"); done(); return } // No loss of continuity expect(stateChange.resumed).to(beTrue()) expect(stateChange.reason).to(beNil()) - expect(stateChange.current).to(equal(ARTRealtimeChannelState.Attached)) - expect(stateChange.previous).to(equal(ARTRealtimeChannelState.Attached)) + expect(stateChange.current).to(equal(ARTRealtimeChannelState.attached)) + expect(stateChange.previous).to(equal(ARTRealtimeChannelState.attached)) partialDone() } } @@ -731,7 +731,7 @@ class RealtimeClientPresence: QuickSpec { fail("Members is nil"); done(); return } expect(members).to(equal(originalMembers)) - expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .Absent })) + expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .absent })) done() } } @@ -755,7 +755,7 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("foo") waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -770,9 +770,9 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(4, done: done) - let localMember = ARTPresenceMessage(clientId: "local1", action: .Enter, connectionId: connectionId, id: "\(connectionId):1:1", timestamp: NSDate()) + let localMember = ARTPresenceMessage(clientId: "local1", action: .enter, connectionId: connectionId, id: "\(connectionId):1:1", timestamp: NSDate() as Date) - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in // Local member channel.presenceMap.add(localMember) partialDone() @@ -783,30 +783,30 @@ class RealtimeClientPresence: QuickSpec { } transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Attached { + if protocolMessage.action == .attached { // Expect a Sync expect(protocolMessage.hasPresence).to(beTrue()) expect(protocolMessage.resumed).to(beFalse()) } - else if protocolMessage.action == .Sync { + else if protocolMessage.action == .sync { transport.beforeProcessingReceivedMessage = nil partialDone() } } // Before the sync ends - channel.presenceMap.testSuite_injectIntoMethodBefore(#selector(ARTPresenceMap.endSync)) { + channel.presenceMap.testSuite_injectIntoMethod(before: #selector(ARTPresenceMap.endSync)) { expect(channel.presenceMap.members).to(haveCount(4)) expect(channel.presenceMap.localMembers).to(haveCount(1)) transport.beforeProcessingSentMessage = { protocolMessage in - if protocolMessage.action == .Presence && protocolMessage.presence?.first?.action == .Enter { + if protocolMessage.action == .presence && protocolMessage.presence?.first?.action == .enter { expect(channel.presenceMap.localMembers).to(beEmpty()) transport.beforeProcessingSentMessage = nil } } // Re-entered automatically - channel.presence.subscribe(.Enter) { enter in + channel.presence.subscribe(.enter) { enter in // The members re-entered automatically must be removed from the internal PresenceMap, //so it must be a different object expect(enter).toNot(beIdenticalTo(localMember)) @@ -824,7 +824,7 @@ class RealtimeClientPresence: QuickSpec { fail("Members is nil"); done(); return } expect(members).to(haveCount(4)) - expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .Absent })) + expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .absent })) done() } } @@ -869,7 +869,7 @@ class RealtimeClientPresence: QuickSpec { fail("TestProxyTransport is not set"); return } transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Attached { + if protocolMessage.action == .attached { expect(protocolMessage.hasPresence).to(beFalse()) expect(protocolMessage.resumed).to(beFalse()) transport.beforeProcessingReceivedMessage = nil @@ -877,7 +877,7 @@ class RealtimeClientPresence: QuickSpec { } } transport.beforeProcessingSentMessage = { protocolMessage in - if protocolMessage.action == .Presence && protocolMessage.presence?.first?.action == .Enter { + if protocolMessage.action == .presence && protocolMessage.presence?.first?.action == .enter { // Re-enter expect(protocolMessage.presence?.first?.clientId).to(equal("local1")) expect(channel.presenceMap.localMembers).to(beEmpty()) @@ -886,24 +886,24 @@ class RealtimeClientPresence: QuickSpec { } } - channel.presence.subscribe(.Leave) { leave in + channel.presence.subscribe(.leave) { leave in // Members will leave the PresenceMap due to the ATTACHED without Presence expect(leave.clientId).to(satisfyAnyOf(equal("local1"), equal("user1"), equal("user2"), equal("user3"))) } // Re-entered automatically - channel.presence.subscribe(.Update) { update in + channel.presence.subscribe(.update) { update in expect(update.clientId) == "local1" partialDone() } - channel.presence.subscribe(.Enter) { enter in + channel.presence.subscribe(.enter) { enter in fail("Members already being present so the client should receive UPDATE events"); done(); return } // Inject ATTACHED message let attached = ARTProtocolMessage() - attached.action = .Attached + attached.action = .attached attached.channel = channel.name attached.flags = 0 //no presence, no resume transport.receive(attached) @@ -940,7 +940,7 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("foo") waitUntil(timeout: testTimeout) { done in - client.connection.once(.Connected) { stateChange in + client.connection.once(.connected) { stateChange in expect(stateChange?.reason).to(beNil()) done() } @@ -955,9 +955,9 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - let localMember = ARTPresenceMessage(clientId: "local1", action: .Enter, connectionId: connectionId, id: "\(connectionId):1:1", timestamp: NSDate()) + let localMember = ARTPresenceMessage(clientId: "local1", action: .enter, connectionId: connectionId, id: "\(connectionId):1:1", timestamp: NSDate() as Date) - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in // Local member channel.presenceMap.add(localMember) partialDone() @@ -965,22 +965,22 @@ class RealtimeClientPresence: QuickSpec { channel.attach() // Before the sync ends - channel.presenceMap.testSuite_injectIntoMethodBefore(#selector(ARTPresenceMap.endSync)) { + channel.presenceMap.testSuite_injectIntoMethod(before: #selector(ARTPresenceMap.endSync)) { expect(channel.presenceMap.members).to(haveCount(4)) expect(channel.presenceMap.localMembers).to(haveCount(1)) // Time out - let reEnterError = ARTErrorInfo.createWithCode(50003, message: "timed out") + let reEnterError = ARTErrorInfo.create(withCode: 50003, message: "timed out") transport.replaceAcksWithNacks(reEnterError) { _ in } // Re-entered automatically should fail - channel.presence.subscribe(.Enter) { enter in + channel.presence.subscribe(.enter) { enter in fail("Should not Enter the local member") } partialDone() } - channel.once(.Update) { stateChange in + channel.once(.update) { stateChange in guard let stateChange = stateChange else { fail("ChannelStateChange is nil"); partialDone(); return } @@ -1002,7 +1002,7 @@ class RealtimeClientPresence: QuickSpec { fail("Members is nil"); done(); return } expect(members).to(haveCount(3)) - expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .Absent })) + expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .absent })) done() } } @@ -1021,13 +1021,13 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in expect(stateChange?.reason).to(beNil()) expect(channel.queuedMessages.count) == 1 - channel.setSuspended(ARTStatus.state(.Error, info: ARTErrorInfo.createWithCode(1234, message: "unknown error"))) + channel.setSuspended(ARTStatus.state(.error, info: ARTErrorInfo.create(withCode: 1234, message: "unknown error"))) partialDone() } - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in // All queued presence messages will fail immediately expect(channel.queuedMessages.count) == 0 partialDone() @@ -1036,7 +1036,7 @@ class RealtimeClientPresence: QuickSpec { guard let error = error else { fail("Error is nil"); partialDone(); return } - expect(error.code) == 1234 + expect((error ).code) == 1234 expect(error.message).to(contain("unknown error")) partialDone() } @@ -1055,7 +1055,7 @@ class RealtimeClientPresence: QuickSpec { defer { clientMembers?.dispose(); clientMembers?.close() } options.clientId = "tester" - options.tokenDetails = getTestTokenDetails(key: options.key!, ttl: 5.0, clientId: options.clientId) + options.tokenDetails = getTestTokenDetails(key: options.key!, clientId: options.clientId, ttl: 5.0) let client = AblyTests.newRealtime(options) defer { client.dispose(); client.close() } let channel = client.channels.get("foo") @@ -1075,16 +1075,16 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(4, done: done) channel.presence.subscribe { presence in - expect(presence.action).to(equal(ARTPresenceAction.Leave)) + expect(presence.action).to(equal(ARTPresenceAction.leave)) expect(presence.clientId).to(equal("tester")) partialDone() } - channel.once(.Suspended) { stateChange in + channel.once(.suspended) { stateChange in expect(channel.presenceMap.members).to(haveCount(4)) expect(channel.presenceMap.localMembers).to(haveCount(1)) partialDone() } - channel.once(.Attaching) { stateChange in + channel.once(.attaching) { stateChange in expect(stateChange?.reason).to(beNil()) channel.presence.leave(nil) { error in expect(error).to(beNil()) @@ -1092,11 +1092,11 @@ class RealtimeClientPresence: QuickSpec { } expect(channel.queuedMessages.count) == 1 } - channel.once(.Attached) { stateChange in + channel.once(.attached) { stateChange in expect(stateChange?.reason).to(beNil()) partialDone() } - channel.setSuspended(ARTStatus.state(.Ok)) + channel.setSuspended(ARTStatus.state(.ok)) } channel.presence.unsubscribe() @@ -1107,7 +1107,7 @@ class RealtimeClientPresence: QuickSpec { fail("Members is nil"); done(); return } expect(members).to(haveCount(3)) - expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .Absent })) + expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .absent })) expect(channel.presenceMap.members).to(haveCount(3)) expect(channel.presenceMap.localMembers).to(beEmpty()) done() @@ -1138,9 +1138,9 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in channel1.attach { err in expect(err).to(beNil()) - channel1.presence.subscribe(.Enter) { member in + channel1.presence.subscribe(.enter) { member in expect(member.clientId).to(equal(options.clientId)) - expect(member.data as? NSObject).to(equal("online")) + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel2.presence.enter("online") @@ -1159,9 +1159,9 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - let listener = channel.presence.subscribe(.Present) { _ in }! + let listener = channel.presence.subscribe(.present) { _ in }! expect(channel.presenceEventEmitter.listeners).to(haveCount(1)) - channel.presence.unsubscribe(.Present, listener: listener) + channel.presence.unsubscribe(.present, listener: listener) expect(channel.presenceEventEmitter.listeners).to(haveCount(0)) } @@ -1176,17 +1176,17 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) channel.presence.subscribe { _ in } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) channel.detach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) - channel.presence.subscribe(.Present) { _ in } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + channel.presence.subscribe(.present) { _ in } + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) } // RTP6c @@ -1196,13 +1196,13 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") channel.onError(AblyTests.newErrorProtocolMessage()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) waitUntil(timeout: testTimeout) { done in - channel.presence.subscribeWithAttachCallback({ errorInfo in + channel.presence.subscribe(attachCallback: { errorInfo in expect(errorInfo).toNot(beNil()) - channel.presence.subscribe(.Enter, onAttach: { errorInfo in + channel.presence.subscribe(.enter, onAttach: { errorInfo in expect(errorInfo).toNot(beNil()) done() }) { _ in } @@ -1218,10 +1218,10 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let error = AblyTests.newErrorProtocolMessage() - channel.presence.subscribeWithAttachCallback({ errorInfo in + channel.presence.subscribe(attachCallback: { errorInfo in expect(errorInfo).toNot(beNil()) - channel.presence.subscribe(.Enter, onAttach: { errorInfo in + channel.presence.subscribe(.enter, onAttach: { errorInfo in expect(errorInfo).toNot(beNil()) done() }) { _ in } @@ -1248,10 +1248,10 @@ class RealtimeClientPresence: QuickSpec { let channel2 = client2.channels.get("test") var count = 0 - channel1.presence.subscribe(.Update) { member in - expect(member.action).to(equal(ARTPresenceAction.Update)) + channel1.presence.subscribe(.update) { member in + expect(member.action).to(equal(ARTPresenceAction.update)) expect(member.clientId).to(equal("john")) - expect(member.data as? NSObject).to(equal("away")) + expect(member.data as? NSObject).to(equal("away" as NSObject?)) count += 1 } @@ -1290,9 +1290,9 @@ class RealtimeClientPresence: QuickSpec { let channel2 = client2.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel1.presence.subscribe(.Enter) { member in + channel1.presence.subscribe(.enter) { member in expect(member.clientId).to(equal(options.clientId)) - expect(member.data as? NSObject).to(equal("online")) + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel2.presence.enter("online") { error in @@ -1315,7 +1315,7 @@ class RealtimeClientPresence: QuickSpec { let channel2 = client2.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel1.presence.subscribe(.Enter) { member in + channel1.presence.subscribe(.enter) { member in fail("shouldn't be called") } let protocolError = AblyTests.newErrorProtocolMessage() @@ -1343,12 +1343,12 @@ class RealtimeClientPresence: QuickSpec { } let transport = client.transport as! TestProxyTransport - let sent = transport.protocolMessagesSent.filter({ $0.action == .Presence })[0].presence![0] - expect(sent.action).to(equal(ARTPresenceAction.Enter)) + let sent = transport.protocolMessagesSent.filter({ $0.action == .presence })[0].presence![0] + expect(sent.action).to(equal(ARTPresenceAction.enter)) expect(sent.clientId).to(beNil()) - let received = transport.protocolMessagesReceived.filter({ $0.action == .Presence })[0].presence![0] - expect(received.action).to(equal(ARTPresenceAction.Enter)) + let received = transport.protocolMessagesReceived.filter({ $0.action == .presence })[0].presence![0] + expect(received.action).to(equal(ARTPresenceAction.enter)) expect(received.clientId).to(equal("john")) } @@ -1390,7 +1390,7 @@ class RealtimeClientPresence: QuickSpec { } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) waitUntil(timeout: testTimeout) { done in channel.presence.enter(nil) { error in @@ -1410,7 +1410,7 @@ class RealtimeClientPresence: QuickSpec { channel.onError(AblyTests.newErrorProtocolMessage()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) waitUntil(timeout: testTimeout) { done in channel.presence.enter(nil) { error in @@ -1453,7 +1453,7 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Enter) { member in + channel.presence.subscribe(.enter) { member in expect(member.data).to(beNil()) done() } @@ -1461,8 +1461,8 @@ class RealtimeClientPresence: QuickSpec { } waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Update) { member in - expect(member.data as? NSObject).to(equal("online")) + channel.presence.subscribe(.update) { member in + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel.presence.update("online") @@ -1478,15 +1478,15 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Enter) { member in - expect(member.data as? NSObject).to(equal("online")) + channel.presence.subscribe(.enter) { member in + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel.presence.enter("online") } waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Update) { member in + channel.presence.subscribe(.update) { member in expect(member.data).to(beNil()) done() } @@ -1509,9 +1509,9 @@ class RealtimeClientPresence: QuickSpec { expect(channel.presenceMap.members).to(haveCount(0)) waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Enter) { member in + channel.presence.subscribe(.enter) { member in expect(member.clientId).to(equal("john")) - expect(member.data as? NSObject).to(equal("online")) + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel.presence.update("online") @@ -1575,14 +1575,14 @@ class RealtimeClientPresence: QuickSpec { } let transport = client.transport as! TestProxyTransport - let sent = transport.protocolMessagesSent.filter({ $0.action == .Presence })[1].presence![0] - expect(sent.action).to(equal(ARTPresenceAction.Update)) + let sent = transport.protocolMessagesSent.filter({ $0.action == .presence })[1].presence![0] + expect(sent.action).to(equal(ARTPresenceAction.update)) expect(sent.clientId).to(beNil()) - let receivedPresenceProtocolMessages = transport.protocolMessagesReceived.filter({ $0.action == .Presence }) + let receivedPresenceProtocolMessages = transport.protocolMessagesReceived.filter({ $0.action == .presence }) let receivedPresenceMessages = receivedPresenceProtocolMessages.flatMap({ $0.presence! }) - let received = receivedPresenceMessages.filter({ $0.action == .Update })[0] - expect(received.action).to(equal(ARTPresenceAction.Update)) + let received = receivedPresenceMessages.filter({ $0.action == .update })[0] + expect(received.action).to(equal(ARTPresenceAction.update)) expect(received.clientId).to(equal("john")) } @@ -1600,8 +1600,8 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Enter) { member in - expect(member.data as? NSObject).to(equal("online")) + channel.presence.subscribe(.enter) { member in + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel.presence.enter("online") @@ -1610,8 +1610,8 @@ class RealtimeClientPresence: QuickSpec { expect(channel.presenceMap.members).toEventually(haveCount(1), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Leave) { member in - expect(member.data as? NSObject).to(equal("offline")) + channel.presence.subscribe(.leave) { member in + expect(member.data as? NSObject).to(equal("offline" as NSObject?)) done() } channel.presence.leave("offline") @@ -1629,16 +1629,16 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Enter) { member in - expect(member.data as? NSObject).to(equal("online")) + channel.presence.subscribe(.enter) { member in + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel.presence.enter("online") } waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Leave) { member in - expect(member.data as? NSObject).to(equal("online")) + channel.presence.subscribe(.leave) { member in + expect(member.data as? NSObject).to(equal("online" as NSObject?)) done() } channel.presence.leave(nil) @@ -1664,16 +1664,16 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") var user50LeaveTimestamp: NSDate? - channel.presence.subscribe(.Leave) { member in + channel.presence.subscribe(.leave) { member in expect(member.clientId).to(equal("user50")) - user50LeaveTimestamp = member.timestamp + user50LeaveTimestamp = member.timestamp as NSDate? } var user50PresentTimestamp: NSDate? - channel.presenceMap.testSuite_getArgumentFrom(#selector(ARTPresenceMap.add(_:)), atIndex: 0) { arg0 in + channel.presenceMap.testSuite_getArgument(from: #selector(ARTPresenceMap.add(_:)), at: 0) { arg0 in let member = arg0 as! ARTPresenceMessage - if member.clientId == "user50" && member.action == .Present { - user50PresentTimestamp = member.timestamp + if member.clientId == "user50" && member.action == .present { + user50PresentTimestamp = member.timestamp as NSDate? } } @@ -1685,10 +1685,10 @@ class RealtimeClientPresence: QuickSpec { } transport.beforeProcessingReceivedMessage = { protocolMessage in // A leave event for a member can arrive before that member is later registered as present as part of the initial SYNC operation. - if protocolMessage.action == .Sync { - let msg = AblyTests.newPresenceProtocolMessage("test", action: .Leave, clientId: "user50") + if protocolMessage.action == .sync { + let msg = AblyTests.newPresenceProtocolMessage("test", action: .leave, clientId: "user50") // Ensure it happens "later" than the PRESENT message. - msg.timestamp = NSDate().dateByAddingTimeInterval(1.0) + msg.timestamp = NSDate().addingTimeInterval(1.0) as Date client.onChannelMessage(msg) done() } @@ -1710,7 +1710,7 @@ class RealtimeClientPresence: QuickSpec { } } - expect(user50LeaveTimestamp).to(beGreaterThan(user50PresentTimestamp)) + expect(user50LeaveTimestamp as Date?).to(beGreaterThan(user50PresentTimestamp as Date?)) } // RTP2 @@ -1737,7 +1737,7 @@ class RealtimeClientPresence: QuickSpec { expect(intialPresenceMessage.memberKey()).to(equal("\(client.connection.id!):tester")) var compareForNewnessMethodCalls = 0 - let hook = channel.presenceMap.testSuite_injectIntoMethodAfter(NSSelectorFromString("isNewestPresence:comparingWith:")) { + let hook = channel.presenceMap.testSuite_injectIntoMethod(after: NSSelectorFromString("isNewestPresence:comparingWith:")) { compareForNewnessMethodCalls += 1 } defer { hook.remove() } @@ -1781,12 +1781,12 @@ class RealtimeClientPresence: QuickSpec { let channelSubscribed = clientSubscribed.channels.get("foo") let presenceData: [ARTPresenceMessage] = [ - ARTPresenceMessage(clientId: "a", action: .Enter, connectionId: "one", id: "one:0:0", timestamp: now), - ARTPresenceMessage(clientId: "a", action: .Leave, connectionId: "one", id: "fabricated:0:1", timestamp: now + 1), - ARTPresenceMessage(clientId: "b", action: .Enter, connectionId: "one", id: "one:0:2", timestamp: now), - ARTPresenceMessage(clientId: "b", action: .Leave, connectionId: "one", id: "fabricated:0:3", timestamp: now - 1), - ARTPresenceMessage(clientId: "c", action: .Enter, connectionId: "one", id: "fabricated:0:4", timestamp: now), - ARTPresenceMessage(clientId: "c", action: .Leave, connectionId: "one", id: "fabricated:0:5", timestamp: now - 1), + ARTPresenceMessage(clientId: "a", action: .enter, connectionId: "one", id: "one:0:0", timestamp: now as Date), + ARTPresenceMessage(clientId: "a", action: .leave, connectionId: "one", id: "fabricated:0:1", timestamp: (now as Date) + 1), + ARTPresenceMessage(clientId: "b", action: .enter, connectionId: "one", id: "one:0:2", timestamp: now as Date), + ARTPresenceMessage(clientId: "b", action: .leave, connectionId: "one", id: "fabricated:0:3", timestamp: (now as Date) - 1), + ARTPresenceMessage(clientId: "c", action: .enter, connectionId: "one", id: "fabricated:0:4", timestamp: now as Date), + ARTPresenceMessage(clientId: "c", action: .leave, connectionId: "one", id: "fabricated:0:5", timestamp: (now as Date) - 1), ] guard let transport = clientSubscribed.transport as? TestProxyTransport else { @@ -1796,31 +1796,31 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in transport.afterProcessingReceivedMessage = { protocolMessage in // Receive the first Sync message from Ably service - if protocolMessage.action == .Sync { + if protocolMessage.action == .sync { // Inject a fabricated Presence message let presenceMessage = ARTProtocolMessage() - presenceMessage.action = .Presence + presenceMessage.action = .presence presenceMessage.channel = protocolMessage.channel presenceMessage.connectionSerial = protocolMessage.connectionSerial + 1 - presenceMessage.timestamp = NSDate() + presenceMessage.timestamp = NSDate() as Date presenceMessage.presence = presenceData transport.receive(presenceMessage) // Simulate an end to the sync let endSyncMessage = ARTProtocolMessage() - endSyncMessage.action = .Sync + endSyncMessage.action = .sync endSyncMessage.channel = protocolMessage.channel endSyncMessage.channelSerial = "validserialprefix:" //with no part after the `:` this indicates the end to the SYNC endSyncMessage.connectionSerial = protocolMessage.connectionSerial + 2 - endSyncMessage.timestamp = NSDate() + endSyncMessage.timestamp = NSDate() as Date transport.afterProcessingReceivedMessage = nil transport.receive(endSyncMessage) // Stop the next sync message from Ably service because we already injected the end of the sync - transport.actionsIgnored = [.Sync] + transport.actionsIgnored = [.sync] done() } @@ -1835,12 +1835,12 @@ class RealtimeClientPresence: QuickSpec { fail("Members is nil"); done(); return } expect(members).to(haveCount(102)) //100 initial members + "b" + "c", client "a" is discarded - expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .Absent })) + expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .absent })) expect(members.filter{ $0.clientId == "a" }).to(beEmpty()) expect(members.filter{ $0.clientId == "b" }).to(haveCount(1)) - expect(members.filter{ $0.clientId == "b" }.first?.timestamp).to(equal(now)) + expect(members.filter{ $0.clientId! == "b" }.first?.timestamp).to(equal(now as Date)) expect(members.filter{ $0.clientId == "c" }).to(haveCount(1)) - expect(members.filter{ $0.clientId == "c" }.first?.timestamp).to(equal(now)) + expect(members.filter{ $0.clientId! == "c" }.first?.timestamp).to(equal(now as Date)) done() } } @@ -1865,12 +1865,12 @@ class RealtimeClientPresence: QuickSpec { let channelSubscribed = clientSubscribed.channels.get("foo") let presenceData: [ARTPresenceMessage] = [ - ARTPresenceMessage(clientId: "a", action: .Enter, connectionId: "one", id: "one:0:0", timestamp: now), - ARTPresenceMessage(clientId: "a", action: .Leave, connectionId: "one", id: "one:1:0", timestamp: now - 1), - ARTPresenceMessage(clientId: "b", action: .Enter, connectionId: "one", id: "one:2:2", timestamp: now), - ARTPresenceMessage(clientId: "b", action: .Leave, connectionId: "one", id: "one:2:1", timestamp: now + 1), - ARTPresenceMessage(clientId: "c", action: .Enter, connectionId: "one", id: "one:4:4", timestamp: now), - ARTPresenceMessage(clientId: "c", action: .Leave, connectionId: "one", id: "one:3:5", timestamp: now + 1), + ARTPresenceMessage(clientId: "a", action: .enter, connectionId: "one", id: "one:0:0", timestamp: now as Date), + ARTPresenceMessage(clientId: "a", action: .leave, connectionId: "one", id: "one:1:0", timestamp: (now as Date) - 1), + ARTPresenceMessage(clientId: "b", action: .enter, connectionId: "one", id: "one:2:2", timestamp: now as Date), + ARTPresenceMessage(clientId: "b", action: .leave, connectionId: "one", id: "one:2:1", timestamp: (now as Date) + 1), + ARTPresenceMessage(clientId: "c", action: .enter, connectionId: "one", id: "one:4:4", timestamp: now as Date), + ARTPresenceMessage(clientId: "c", action: .leave, connectionId: "one", id: "one:3:5", timestamp: (now as Date) + 1), ] guard let transport = clientSubscribed.transport as? TestProxyTransport else { @@ -1880,31 +1880,31 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in transport.afterProcessingReceivedMessage = { protocolMessage in // Receive the first Sync message from Ably service - if protocolMessage.action == .Sync { + if protocolMessage.action == .sync { // Inject a fabricated Presence message let presenceMessage = ARTProtocolMessage() - presenceMessage.action = .Presence + presenceMessage.action = .presence presenceMessage.channel = protocolMessage.channel presenceMessage.connectionSerial = protocolMessage.connectionSerial + 1 - presenceMessage.timestamp = NSDate() + presenceMessage.timestamp = NSDate() as Date presenceMessage.presence = presenceData transport.receive(presenceMessage) // Simulate an end to the sync let endSyncMessage = ARTProtocolMessage() - endSyncMessage.action = .Sync + endSyncMessage.action = .sync endSyncMessage.channel = protocolMessage.channel endSyncMessage.channelSerial = "validserialprefix:" //with no part after the `:` this indicates the end to the SYNC endSyncMessage.connectionSerial = protocolMessage.connectionSerial + 2 - endSyncMessage.timestamp = NSDate() + endSyncMessage.timestamp = NSDate() as Date transport.afterProcessingReceivedMessage = nil transport.receive(endSyncMessage) // Stop the next sync message from Ably service because we already injected the end of the sync - transport.actionsIgnored = [.Sync] + transport.actionsIgnored = [.sync] done() } @@ -1919,12 +1919,12 @@ class RealtimeClientPresence: QuickSpec { fail("Members is nil"); done(); return } expect(members).to(haveCount(102)) //100 initial members + "b" + "c", client "a" is discarded - expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .Absent })) + expect(members).to(allPass({ (member: ARTPresenceMessage?) in member!.action != .absent })) expect(members.filter{ $0.clientId == "a" }).to(beEmpty()) expect(members.filter{ $0.clientId == "b" }).to(haveCount(1)) - expect(members.filter{ $0.clientId == "b" }.first?.timestamp).to(equal(now)) + expect(members.filter{ $0.clientId! == "b" }.first?.timestamp).to(equal(now as Date)) expect(members.filter{ $0.clientId == "c" }).to(haveCount(1)) - expect(members.filter{ $0.clientId == "c" }.first?.timestamp).to(equal(now)) + expect(members.filter{ $0.clientId! == "c" }.first?.timestamp).to(equal(now as Date)) done() } } @@ -1958,7 +1958,7 @@ class RealtimeClientPresence: QuickSpec { fail("TestProxyTransport is not set"); return } - channel.presence.subscribe(.Leave) { leave in + channel.presence.subscribe(.leave) { leave in expect(leave.clientId).to(equal("user110")) fail("Should not fire Leave event for member `user110` because it's out of date") } @@ -1966,21 +1966,21 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Sync { + if protocolMessage.action == .sync { let injectLeave = ARTPresenceMessage() - injectLeave.action = .Leave + injectLeave.action = .leave injectLeave.connectionId = membersConnectionId injectLeave.clientId = "user110" - injectLeave.timestamp = timeBeforeSync + injectLeave.timestamp = timeBeforeSync as Date protocolMessage.presence?.append(injectLeave) transport.beforeProcessingReceivedMessage = nil partialDone() } } - channel.presenceMap.testSuite_injectIntoMethodAfter(#selector(ARTPresenceMap.endSync)) { + channel.presenceMap.testSuite_injectIntoMethod(after: #selector(ARTPresenceMap.endSync)) { expect(channel.presenceMap.syncInProgress).to(beFalse()) expect(channel.presenceMap.members).to(haveCount(120)) - expect(channel.presenceMap.members.filter{ _, presence in presence.clientId == "user110" && presence.action == .Present }).to(haveCount(1)) + expect(channel.presenceMap.members.filter{ _, presence in presence.clientId == "user110" && presence.action == .present }).to(haveCount(1)) partialDone() } channel.attach() { error in @@ -2014,23 +2014,23 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(4, done: done) - channel.presence.subscribe(.Leave) { leave in + channel.presence.subscribe(.leave) { leave in expect(leave.clientId).to(equal("user110")) partialDone() } transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Sync { + if protocolMessage.action == .sync { let injectLeave = ARTPresenceMessage() - injectLeave.action = .Leave + injectLeave.action = .leave injectLeave.connectionId = membersConnectionId injectLeave.clientId = "user110" - injectLeave.timestamp = NSDate() + 1 + injectLeave.timestamp = (NSDate() as Date) + 1 protocolMessage.presence?.append(injectLeave) transport.beforeProcessingReceivedMessage = nil partialDone() } } - channel.presenceMap.testSuite_injectIntoMethodAfter(#selector(ARTPresenceMap.endSync)) { + channel.presenceMap.testSuite_injectIntoMethod(after: #selector(ARTPresenceMap.endSync)) { expect(channel.presenceMap.syncInProgress).to(beFalse()) expect(channel.presenceMap.members).to(haveCount(119)) expect(channel.presenceMap.members.filter{ _, presence in presence.clientId == "user110" }).to(beEmpty()) @@ -2054,7 +2054,7 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.presence.subscribe(.Enter) { _ in + channel.presence.subscribe(.enter) { _ in partialDone() } channel.presence.enterClient("tester", data: nil) { error in @@ -2063,8 +2063,8 @@ class RealtimeClientPresence: QuickSpec { } } - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Present }).to(haveCount(1)) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Enter }).to(beEmpty()) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .present }).to(haveCount(1)) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .enter }).to(beEmpty()) } // RTP2d @@ -2076,7 +2076,7 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - channel.presence.subscribe(.Update) { _ in + channel.presence.subscribe(.update) { _ in partialDone() } channel.presence.enterClient("tester", data: nil) { error in @@ -2090,8 +2090,8 @@ class RealtimeClientPresence: QuickSpec { } expect(channel.presenceMap.members).to(haveCount(1)) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Present }).to(haveCount(1)) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Update }).to(beEmpty()) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .present }).to(haveCount(1)) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .update }).to(beEmpty()) } // RTP2d @@ -2112,7 +2112,7 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(2, done: done) - channel.presenceMap.testSuite_injectIntoMethodAfter(#selector(ARTPresenceMap.endSync)) { + channel.presenceMap.testSuite_injectIntoMethod(after: #selector(ARTPresenceMap.endSync)) { expect(channel.presenceMap.syncInProgress).to(beFalse()) partialDone() } @@ -2147,7 +2147,7 @@ class RealtimeClientPresence: QuickSpec { } waitUntil(timeout: testTimeout) { done in transport.afterProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Sync { + if protocolMessage.action == .sync { done() } } @@ -2160,7 +2160,7 @@ class RealtimeClientPresence: QuickSpec { } waitUntil(timeout: testTimeout) { done in - channel.presence.subscribe(.Leave) { presence in + channel.presence.subscribe(.leave) { presence in expect(presence.clientId).to(equal("user11")) done() } @@ -2193,35 +2193,35 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let partialDone = AblyTests.splitDone(3, done: done) - channel.presenceMap.testSuite_injectIntoMethodAfter(#selector(ARTPresenceMap.startSync)) { + channel.presenceMap.testSuite_injectIntoMethod(after: #selector(ARTPresenceMap.startSync)) { expect(channel.presenceMap.syncInProgress).to(beTrue()) - channel.presence.subscribe(.Leave) { leave in + channel.presence.subscribe(.leave) { leave in expect(leave.clientId).to(equal("user11")) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Leave }).to(beEmpty()) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Absent }).to(haveCount(1)) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .leave }).to(beEmpty()) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .absent }).to(haveCount(1)) partialDone() } // Inject a fabricated Presence message let leaveMessage = ARTProtocolMessage() - leaveMessage.action = .Presence + leaveMessage.action = .presence leaveMessage.channel = channel.name leaveMessage.connectionSerial = client.connection.serial + 1 - leaveMessage.timestamp = NSDate() + leaveMessage.timestamp = NSDate() as Date leaveMessage.presence = [ - ARTPresenceMessage(clientId: "user11", action: .Leave, connectionId: "another", id: "another:123:0", timestamp: NSDate()) + ARTPresenceMessage(clientId: "user11", action: .leave, connectionId: "another", id: "another:123:0", timestamp: NSDate() as Date) ] transport.receive(leaveMessage) } - channel.presenceMap.testSuite_injectIntoMethodBefore(#selector(ARTPresenceMap.endSync)) { - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Absent }).to(haveCount(1)) + channel.presenceMap.testSuite_injectIntoMethod(before: #selector(ARTPresenceMap.endSync)) { + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .absent }).to(haveCount(1)) partialDone() } - channel.presenceMap.testSuite_injectIntoMethodAfter(#selector(ARTPresenceMap.endSync)) { + channel.presenceMap.testSuite_injectIntoMethod(after: #selector(ARTPresenceMap.endSync)) { expect(channel.presenceMap.syncInProgress).to(beFalse()) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Leave }).to(beEmpty()) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Absent }).to(beEmpty()) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .leave }).to(beEmpty()) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .absent }).to(beEmpty()) partialDone() } } @@ -2242,13 +2242,13 @@ class RealtimeClientPresence: QuickSpec { expect(error).to(beNil()) partialDone() } - channel.presence.subscribe(.Enter) { _ in + channel.presence.subscribe(.enter) { _ in partialDone() } } - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Present }).to(haveCount(1)) - expect(channel.presenceMap.members.filter{ _, presence in presence.action == .Enter }).to(beEmpty()) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .present }).to(haveCount(1)) + expect(channel.presenceMap.members.filter{ _, presence in presence.action == .enter }).to(beEmpty()) } } @@ -2304,7 +2304,7 @@ class RealtimeClientPresence: QuickSpec { channel.attach() channel.detach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.presence.update(nil) { error in @@ -2418,7 +2418,7 @@ class RealtimeClientPresence: QuickSpec { } waitUntil(timeout: testTimeout) { done in - let sentError = ARTErrorInfo.createWithCode(0, message: "test error") + let sentError = ARTErrorInfo.create(withCode: 0, message: "test error") let transport = client.transport as! TestProxyTransport transport.replaceAcksWithNacks(sentError) { doneReplacing in channel.presence.leave("offline") { error in @@ -2458,14 +2458,14 @@ class RealtimeClientPresence: QuickSpec { let transport = client.transport as! TestProxyTransport - let sent = transport.protocolMessagesSent.filter({ $0.action == .Presence })[1].presence![0] - expect(sent.action).to(equal(ARTPresenceAction.Leave)) + let sent = transport.protocolMessagesSent.filter({ $0.action == .presence })[1].presence![0] + expect(sent.action).to(equal(ARTPresenceAction.leave)) expect(sent.clientId).to(beNil()) - let receivedPresenceProtocolMessages = transport.protocolMessagesReceived.filter({ $0.action == .Presence }) + let receivedPresenceProtocolMessages = transport.protocolMessagesReceived.filter({ $0.action == .presence }) let receivedPresenceMessages = receivedPresenceProtocolMessages.flatMap({ $0.presence! }) - let received = receivedPresenceMessages.filter({ $0.action == .Leave })[0] - expect(received.action).to(equal(ARTPresenceAction.Leave)) + let received = receivedPresenceMessages.filter({ $0.action == .leave })[0] + expect(received.action).to(equal(ARTPresenceAction.leave)) expect(received.clientId).to(equal("john")) } @@ -2483,15 +2483,15 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) waitUntil(timeout: testTimeout) { done in channel.presence.enter("online") { error in expect(error).to(beNil()) done() } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) } // RTP8d @@ -2511,7 +2511,7 @@ class RealtimeClientPresence: QuickSpec { done() } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) } // RTP8d @@ -2534,7 +2534,7 @@ class RealtimeClientPresence: QuickSpec { partialDone() } } - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) waitUntil(timeout: testTimeout) { done in channel.presence.enter("online") { error in @@ -2655,17 +2655,17 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) channel.presence.subscribe { _ in } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) channel.detach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) - channel.presence.subscribe(.Present) { _ in } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + channel.presence.subscribe(.present) { _ in } + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) } // RTP6c @@ -2678,8 +2678,8 @@ class RealtimeClientPresence: QuickSpec { channel.onError(protocolError) waitUntil(timeout: testTimeout) { done in - channel.presence.subscribeWithAttachCallback({ error in - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + channel.presence.subscribe(attachCallback: { error in + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(error).toNot(beNil()) done() }, callback: { member in @@ -2696,8 +2696,8 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in let error = AblyTests.newErrorProtocolMessage() - channel.presence.subscribeWithAttachCallback({ error in - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + channel.presence.subscribe(attachCallback: { error in + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(error).toNot(beNil()) done() }, callback: { member in @@ -2732,8 +2732,8 @@ class RealtimeClientPresence: QuickSpec { channel1.attach { error in expect(error).to(beNil()) let partlyDone = AblyTests.splitDone(2, done: done) - channel1.presence.subscribe(.Enter) { member in - expect(member.data as? NSObject).to(equal(expectedData)) + channel1.presence.subscribe(.enter) { member in + expect(member.data as? NSObject).to(equal(expectedData as NSObject?)) partlyDone() } channel2.presence.enter(expectedData) { error in @@ -2771,8 +2771,8 @@ class RealtimeClientPresence: QuickSpec { channel1.attach { err in expect(err).to(beNil()) let partlyDone = AblyTests.splitDone(2, done: done) - channel1.presence.subscribe(.Leave) { member in - expect(member.data as? NSObject).to(equal(expectedData)) + channel1.presence.subscribe(.leave) { member in + expect(member.data as? NSObject).to(equal(expectedData as NSObject?)) partlyDone() } channel2.presence.leave(nil) { error in @@ -2808,7 +2808,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientA.connection.id else { fail("ClientA should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Enter)) + expect(presence.action).to(equal(ARTPresenceAction.enter)) expect(presence.connectionId).to(equal(currentConnectionId)) expect(channelA.presenceMap.members).to(haveCount(1)) expect(channelA.presenceMap.localMembers).to(haveCount(1)) @@ -2819,7 +2819,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientB.connection.id else { fail("ClientB should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Enter)) + expect(presence.action).to(equal(ARTPresenceAction.enter)) expect(presence.connectionId).toNot(equal(currentConnectionId)) expect(channelB.presenceMap.members).to(haveCount(1)) expect(channelB.presenceMap.localMembers).to(haveCount(0)) @@ -2835,7 +2835,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientA.connection.id else { fail("ClientA should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Enter)) + expect(presence.action).to(equal(ARTPresenceAction.enter)) expect(presence.connectionId).toNot(equal(currentConnectionId)) expect(channelA.presenceMap.members).to(haveCount(2)) expect(channelA.presenceMap.localMembers).to(haveCount(1)) @@ -2846,7 +2846,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientB.connection.id else { fail("ClientB should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Enter)) + expect(presence.action).to(equal(ARTPresenceAction.enter)) expect(presence.connectionId).to(equal(currentConnectionId)) expect(channelB.presenceMap.members).to(haveCount(2)) expect(channelB.presenceMap.localMembers).to(haveCount(1)) @@ -2863,7 +2863,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientA.connection.id else { fail("ClientA should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Update)) + expect(presence.action).to(equal(ARTPresenceAction.update)) expect(presence.data as? String).to(equal("hello")) expect(presence.connectionId).toNot(equal(currentConnectionId)) expect(channelA.presenceMap.members).to(haveCount(2)) @@ -2875,7 +2875,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientB.connection.id else { fail("ClientB should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Update)) + expect(presence.action).to(equal(ARTPresenceAction.update)) expect(presence.data as? String).to(equal("hello")) expect(presence.connectionId).to(equal(currentConnectionId)) expect(channelB.presenceMap.members).to(haveCount(2)) @@ -2893,7 +2893,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientA.connection.id else { fail("ClientA should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Leave)) + expect(presence.action).to(equal(ARTPresenceAction.leave)) expect(presence.data as? String).to(equal("bye")) expect(presence.connectionId).toNot(equal(currentConnectionId)) expect(channelA.presenceMap.members).to(haveCount(1)) @@ -2905,7 +2905,7 @@ class RealtimeClientPresence: QuickSpec { guard let currentConnectionId = clientB.connection.id else { fail("ClientB should be connected"); partialDone(); return } - expect(presence.action).to(equal(ARTPresenceAction.Leave)) + expect(presence.action).to(equal(ARTPresenceAction.leave)) expect(presence.data as? String).to(equal("bye")) expect(presence.connectionId).to(equal(currentConnectionId)) expect(channelB.presenceMap.members).to(haveCount(1)) @@ -3017,16 +3017,16 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) waitUntil(timeout: testTimeout) { done in //Call: enterClient, updateClient and leaveClient performMethod(channel.presence) { errorInfo in expect(errorInfo).to(beNil()) done() } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) } it("should result in an error if the channel is in the FAILED state") { @@ -3101,11 +3101,11 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.presence.enterClient("user", data: nil) { error in expect(error).to(beNil()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(channel.queuedMessages).to(haveCount(0)) done() } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connecting)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connecting)) expect(channel.queuedMessages).to(haveCount(1)) } } @@ -3129,11 +3129,11 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.presence.enterClient("user", data: nil) { error in expect(error).to(beNil()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Connected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.connected)) expect(channel.queuedMessages).to(haveCount(0)) done() } - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Disconnected)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.disconnected)) expect(channel.queuedMessages).to(haveCount(1)) } } @@ -3148,7 +3148,7 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") expect(client.options.queueMessages).to(beFalse()) - expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.Connected), timeout: testTimeout) + expect(client.connection.state).toEventually(equal(ARTRealtimeConnectionState.connected), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in channel.attach() { _ in @@ -3175,7 +3175,7 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") expect(client.options.queueMessages).to(beTrue()) - expect(client.connection.state).to(equal(ARTRealtimeConnectionState.Initialized)) + expect(client.connection.state).to(equal(ARTRealtimeConnectionState.initialized)) waitUntil(timeout: testTimeout) { done in channel.presence.enterClient("user", data: nil) { error in @@ -3189,9 +3189,9 @@ class RealtimeClientPresence: QuickSpec { // RTP16c let cases: [ARTRealtimeConnectionState:(ARTRealtime)->()] = [ - .Suspended: { client in client.onSuspended() }, - .Closed: { client in client.close() }, - .Failed: { client in client.onError(AblyTests.newErrorProtocolMessage()) } + .suspended: { client in client.onSuspended() }, + .closed: { client in client.close() }, + .failed: { client in client.onError(AblyTests.newErrorProtocolMessage()) } ] for (connectionState, performMethod) in cases { it("should result in an error if the connection state is \(connectionState)") { @@ -3245,7 +3245,7 @@ class RealtimeClientPresence: QuickSpec { let expectedData = "online" waitUntil(timeout: testTimeout) { done in - disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 150, data:expectedData, options: options) { + disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 150, data:expectedData as AnyObject?, options: options) { done() }] } @@ -3264,10 +3264,10 @@ class RealtimeClientPresence: QuickSpec { channel.presence.get { members, error in expect(error).to(beNil()) expect(members).to(haveCount(150)) - expect(members!.first).to(beAnInstanceOf(ARTPresenceMessage)) + expect(members!.first).to(beAnInstanceOf(ARTPresenceMessage.self)) expect(members).to(allPass({ member in return NSRegularExpression.match(member!.clientId, pattern: "^user(\\d+)$") - && (member!.data as? NSObject) == expectedData + && (member!.data as? String) == expectedData })) done() } @@ -3282,16 +3282,16 @@ class RealtimeClientPresence: QuickSpec { defer { client.dispose(); client.close() } let channel = client.channels.get("test") - expect(channel.state).to(equal(ARTRealtimeChannelState.Initialized)) + expect(channel.state).to(equal(ARTRealtimeChannelState.initialized)) waitUntil(timeout: testTimeout) { done in channel.presence.get() { membersPage, error in expect(error).to(beNil()) expect(membersPage).toNot(beNil()) done() } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attaching)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attaching)) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Attached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.attached)) } // RTP11b @@ -3310,7 +3310,7 @@ class RealtimeClientPresence: QuickSpec { fail("Channel error is empty"); return } expect(channelError.message).to(equal(protocolError.message)) - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) waitUntil(timeout: testTimeout) { done in channel.presence.get() { members, error in @@ -3319,7 +3319,7 @@ class RealtimeClientPresence: QuickSpec { } expect(error.message).to(equal("invalid channel state")) expect(channel.errorReason).to(equal(protocolError)) - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) expect(members).to(beNil()) done() } @@ -3348,7 +3348,7 @@ class RealtimeClientPresence: QuickSpec { channel.onError(pm) } - expect(channel.state).to(equal(ARTRealtimeChannelState.Failed)) + expect(channel.state).to(equal(ARTRealtimeChannelState.failed)) } // RTP11b @@ -3372,7 +3372,7 @@ class RealtimeClientPresence: QuickSpec { } expect(error.message).to(equal("invalid channel state")) expect(members).to(beNil()) - expect(channel.state).to(equal(ARTRealtimeChannelState.Detached)) + expect(channel.state).to(equal(ARTRealtimeChannelState.detached)) done() } } @@ -3410,7 +3410,7 @@ class RealtimeClientPresence: QuickSpec { } } - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Detached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.detached), timeout: testTimeout) } // RTP11c @@ -3440,7 +3440,7 @@ class RealtimeClientPresence: QuickSpec { expect(error).to(beNil()) let transport = client.transport as! TestProxyTransport transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Sync { + if protocolMessage.action == .sync { expect(protocolMessage.presence!.count).to(equal(100)) channel.presence.get(query) { members, error in expect(error).to(beNil()) @@ -3478,7 +3478,7 @@ class RealtimeClientPresence: QuickSpec { expect(error).to(beNil()) let transport = client.transport as! TestProxyTransport transport.beforeProcessingReceivedMessage = { message in - if message.action == .Sync && channel.isLastChannelSerial(message.channelSerial!) { + if message.action == .sync && channel.isLastSerial(message.channelSerial!) { channel.presence.get(query) { members, error in expect(error).to(beNil()) expect(members).to(haveCount(100)) @@ -3516,9 +3516,9 @@ class RealtimeClientPresence: QuickSpec { let channelRealtime = realtime.channels.get("test") let queryRealtime = ARTRealtimeHistoryQuery() - queryRealtime.start = NSDate() - queryRealtime.end = NSDate() - queryRealtime.direction = .Forwards + queryRealtime.start = NSDate() as Date + queryRealtime.end = NSDate() as Date + queryRealtime.direction = .forwards queryRealtime.limit = 50 let queryRest = queryRealtime as ARTDataQuery @@ -3554,7 +3554,7 @@ class RealtimeClientPresence: QuickSpec { let expectedData = ["x", "y"] let expectedPattern = "^user(\\d+)$" waitUntil(timeout: testTimeout) { done in - clientSecondary = AblyTests.addMembersSequentiallyToChannel("test", members: 150, data: expectedData, options: options) { + clientSecondary = AblyTests.addMembersSequentiallyToChannel("test", members: 150, data: expectedData as AnyObject?, options: options) { done() } } @@ -3568,13 +3568,13 @@ class RealtimeClientPresence: QuickSpec { expect(error).to(beNil()) let membersPage = membersPage! - expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult)) + expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult.self)) expect(membersPage.items).to(haveCount(100)) - let members = membersPage.items as! [ARTPresenceMessage] + let members = membersPage.items expect(members).to(allPass({ member in return NSRegularExpression.match(member!.clientId, pattern: expectedPattern) - && (member!.data as? NSObject) == expectedData + && (member!.data as! [String]) == expectedData })) expect(membersPage.hasNext).to(beTrue()) @@ -3583,13 +3583,13 @@ class RealtimeClientPresence: QuickSpec { membersPage.next { nextPage, error in expect(error).to(beNil()) let nextPage = nextPage! - expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult)) + expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult.self)) expect(nextPage.items).to(haveCount(50)) - let members = nextPage.items as! [ARTPresenceMessage] + let members = nextPage.items expect(members).to(allPass({ member in return NSRegularExpression.match(member!.clientId, pattern: expectedPattern) - && (member!.data as? NSObject) == expectedData + && (member!.data as! [String]) == expectedData })) expect(nextPage.hasNext).to(beFalse()) @@ -3625,7 +3625,7 @@ class RealtimeClientPresence: QuickSpec { try channel.presence.history(query, callback: { _, _ in }) } catch let error as NSError { - if error.code == ARTRealtimeHistoryError.NotAttached.rawValue { + if (error as! ARTErrorInfo).code == ARTRealtimeHistoryError.notAttached.rawValue { return } fail("Shouldn't raise a global error, got \(error)") @@ -3652,7 +3652,7 @@ class RealtimeClientPresence: QuickSpec { query.untilAttach = caseItem.untilAttach channel.attach() - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) waitUntil(timeout: testTimeout) { done in try! channel.presence.history(query) { _, errorInfo in @@ -3661,7 +3661,7 @@ class RealtimeClientPresence: QuickSpec { } } - let queryString = testHTTPExecutor.requests.last!.URL!.query + let queryString = testHTTPExecutor.requests.last!.url!.query if query.untilAttach { expect(queryString).to(contain("fromSerial=\(channel.attachSerial!)")) @@ -3699,7 +3699,7 @@ class RealtimeClientPresence: QuickSpec { } waitUntil(timeout: testTimeout) { done in - disposable += [AblyTests.addMembersSequentiallyToChannel("test", startFrom: 26, members: 35, options: options) { + disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 35, startFrom: 26, options: options) { done() }] } @@ -3711,8 +3711,8 @@ class RealtimeClientPresence: QuickSpec { try! channel.presence.history(query) { result, errorInfo in expect(result!.items).to(haveCount(25)) expect(result!.hasNext).to(beFalse()) - expect((result!.items.first as? ARTPresenceMessage)?.clientId).to(equal("user25")) - expect((result!.items.last as? ARTPresenceMessage)?.clientId).to(equal("user1")) + expect((result!.items.first)?.clientId).to(equal("user25")) + expect((result!.items.last)?.clientId).to(equal("user1")) done() } } @@ -3745,18 +3745,18 @@ class RealtimeClientPresence: QuickSpec { let channel = client.channels.get("test") channel.attach() - expect(channel.presence.syncComplete).to(beFalse()) - expect(channel.state).toEventually(equal(ARTRealtimeChannelState.Attached), timeout: testTimeout) + expect(channel.presence.getSyncComplete).to(beFalse()) + expect(channel.state).toEventually(equal(ARTRealtimeChannelState.attached), timeout: testTimeout) let transport = client.transport as! TestProxyTransport transport.beforeProcessingReceivedMessage = { protocolMessage in - if protocolMessage.action == .Sync { - expect(channel.presence.syncComplete).to(beFalse()) + if protocolMessage.action == .sync { + expect(channel.presence.getSyncComplete).to(beFalse()) } } - expect(channel.presence.syncComplete).toEventually(beTrue(), timeout: testTimeout) - expect(transport.protocolMessagesReceived.filter({ $0.action == .Sync })).to(haveCount(3)) + expect(channel.presence.getSyncComplete).toEventually(beTrue(), timeout: testTimeout) + expect(transport.protocolMessagesReceived.filter({ $0.action == .sync })).to(haveCount(3)) } // RTP14 @@ -3772,13 +3772,13 @@ class RealtimeClientPresence: QuickSpec { let expectedData = ["test":1] var encodeNumberOfCalls = 0 - let hookEncode = channel.dataEncoder.testSuite_injectIntoMethodAfter(#selector(ARTDataEncoder.encode(_:))) { + let hookEncode = channel.dataEncoder.testSuite_injectIntoMethod(after: #selector(ARTDataEncoder.encode(_:))) { encodeNumberOfCalls += 1 } defer { hookEncode.remove() } var decodeNumberOfCalls = 0 - let hookDecode = channel.dataEncoder.testSuite_injectIntoMethodAfter(#selector(ARTDataEncoder.decode(_:encoding:))) { + let hookDecode = channel.dataEncoder.testSuite_injectIntoMethod(after: #selector(ARTDataEncoder.decode(_:encoding:))) { decodeNumberOfCalls += 1 } defer { hookDecode.remove() } @@ -3797,11 +3797,11 @@ class RealtimeClientPresence: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.presence.get() { members, error in - guard let members = members?.reduce([String:ARTPresenceMessage](), combine: { (dictionary, item) in + guard let members = members?.reduce([String:ARTPresenceMessage](), { (dictionary, item) in return dictionary + [item.clientId ?? "":item] }) else { fail("No members"); done(); return } - expect(members["test"]!.data as? NSDictionary).to(equal(expectedData)) + expect(members["test"]!.data as? NSDictionary).to(equal(expectedData as NSDictionary?)) expect(members["john"]).toNot(beNil()) expect(members["sara"]).toNot(beNil()) done() diff --git a/Spec/RestClient.swift b/Spec/RestClient.swift index 4c333dbbf..dc3ef46bb 100644 --- a/Spec/RestClient.swift +++ b/Spec/RestClient.swift @@ -110,14 +110,14 @@ class RestClient: QuickSpec { options.logHandler = ARTLog(capturingOutput: true) let client = ARTRest(options: options) - client.logger.log("This is a warning", withLevel: .Warn) + client.logger.log("This is a warning", with: .warn) - expect(client.logger.logLevel).to(equal(ARTLogLevel.Warn)) + expect(client.logger.logLevel).to(equal(ARTLogLevel.warn)) guard let line = options.logHandler.captured.last else { fail("didn't log line.") return } - expect(line.level).to(equal(ARTLogLevel.Warn)) + expect(line.level).to(equal(ARTLogLevel.warn)) expect(line.toString()).to(equal("WARN: This is a warning")) } @@ -126,22 +126,22 @@ class RestClient: QuickSpec { let options = AblyTests.commonAppSetup() options.logHandler = ARTLog(capturingOutput: true) let client = ARTRest(options: options) - client.logger.logLevel = .Error + client.logger.logLevel = .error let logTime = NSDate() - client.logger.log("This is a warning", withLevel: .Warn) + client.logger.log("This is a warning", with: .warn) - let logs = options.logHandler.captured.filter({!$0.date.isBefore(logTime)}) + let logs = options.logHandler.captured.filter({!$0.date.isBefore(logTime as Date)}) expect(logs).to(beEmpty()) } // RSC4 it("should accept a custom logger") { struct Log { - static var interceptedLog: (String, ARTLogLevel) = ("", .None) + static var interceptedLog: (String, ARTLogLevel) = ("", .none) } class MyLogger : ARTLog { - override func log(message: String, withLevel level: ARTLogLevel) { + override func log(_ message: String, with level: ARTLogLevel) { Log.interceptedLog = (message, level) } } @@ -149,13 +149,13 @@ class RestClient: QuickSpec { let options = AblyTests.commonAppSetup() let customLogger = MyLogger() options.logHandler = customLogger - options.logLevel = .Verbose + options.logLevel = .verbose let client = ARTRest(options: options) - client.logger.log("This is a warning", withLevel: .Warn) + client.logger.log("This is a warning", with: .warn) expect(Log.interceptedLog.0).to(equal("This is a warning")) - expect(Log.interceptedLog.1).to(equal(ARTLogLevel.Warn)) + expect(Log.interceptedLog.1).to(equal(ARTLogLevel.warn)) expect(client.logger.logLevel).to(equal(customLogger.logLevel)) } @@ -171,7 +171,7 @@ class RestClient: QuickSpec { publishTestMessage(client, failOnError: false) - expect(testHTTPExecutor.requests.first?.URL?.host).toEventually(equal("fake.ably.io"), timeout: testTimeout) + expect(testHTTPExecutor.requests.first?.url?.host).toEventually(equal("fake.ably.io"), timeout: testTimeout) } it("should ignore an environment when restHost is customized") { @@ -183,7 +183,7 @@ class RestClient: QuickSpec { publishTestMessage(client, failOnError: false) - expect(testHTTPExecutor.requests.first?.URL?.host).toEventually(equal("fake.ably.io"), timeout: testTimeout) + expect(testHTTPExecutor.requests.first?.url?.host).toEventually(equal("fake.ably.io"), timeout: testTimeout) } it("should accept an environment when restHost is left unchanged") { @@ -194,7 +194,7 @@ class RestClient: QuickSpec { publishTestMessage(client, failOnError: false) - expect(testHTTPExecutor.requests.first?.URL?.host).toEventually(equal("myEnvironment-rest.ably.io"), timeout: testTimeout) + expect(testHTTPExecutor.requests.first?.url?.host).toEventually(equal("myEnvironment-rest.ably.io"), timeout: testTimeout) } it("should default to https://rest.ably.io") { @@ -204,7 +204,7 @@ class RestClient: QuickSpec { publishTestMessage(client, failOnError: false) - expect(testHTTPExecutor.requests.first?.URL?.absoluteString).toEventually(beginWith("https://rest.ably.io"), timeout: testTimeout) + expect(testHTTPExecutor.requests.first?.url?.absoluteString).toEventually(beginWith("https://rest.ably.io"), timeout: testTimeout) } it("should connect over plain http:// when tls is off") { @@ -215,7 +215,7 @@ class RestClient: QuickSpec { publishTestMessage(client, failOnError: false) - expect(testHTTPExecutor.requests.first?.URL?.scheme).toEventually(equal("http"), timeout: testTimeout) + expect(testHTTPExecutor.requests.first?.url?.scheme).toEventually(equal("http"), timeout: testTimeout) } it("should not prepend the environment if environment is configured as @production@") { @@ -241,10 +241,10 @@ class RestClient: QuickSpec { let start = NSDate() channel.publish(nil, data: "message") { error in let end = NSDate() - expect(end.timeIntervalSinceDate(start)).to(beCloseTo(options.httpRequestTimeout, within: 0.5)) + expect(end.timeIntervalSince(start as Date)).to(beCloseTo(options.httpRequestTimeout, within: 0.5)) expect(error).toNot(beNil()) if let error = error { - expect(error.code).to(satisfyAnyOf(equal(-1001 /*Timed Out*/), equal(-1004 /*Cannot Connect To Host*/))) + expect((error ).code).to(satisfyAnyOf(equal(-1001 /*Timed Out*/), equal(-1004 /*Cannot Connect To Host*/))) } done() } @@ -257,11 +257,11 @@ class RestClient: QuickSpec { options.httpMaxRetryCount = 1 let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) var totalRetry: UInt = 0 testHTTPExecutor.afterRequest = { request, _ in - if NSRegularExpression.match(request.URL!.absoluteString, pattern: "//[a-e].ably-realtime.com") { + if NSRegularExpression.match(request.url!.absoluteString, pattern: "//[a-e].ably-realtime.com") { totalRetry += 1 } } @@ -281,13 +281,13 @@ class RestClient: QuickSpec { options.httpMaxRetryDuration = 1.0 let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .RequestTimeout(timeout: 0.1)) + testHTTPExecutor.http = MockHTTP(network: .requestTimeout(timeout: 0.1)) let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in let start = NSDate() channel.publish(nil, data: "nil") { _ in let end = NSDate() - expect(end.timeIntervalSinceDate(start)).to(beCloseTo(options.httpMaxRetryDuration, within: 0.9)) + expect(end.timeIntervalSince(start as Date)).to(beCloseTo(options.httpMaxRetryDuration, within: 0.9)) done() } } @@ -318,7 +318,7 @@ class RestClient: QuickSpec { done() } } - expect(testHTTPExecutor.requests.first!.URL!.absoluteString).to(contain("//rest.ably.test")) + expect(testHTTPExecutor.requests.first!.url!.absoluteString).to(contain("//rest.ably.test")) } // RSC16 @@ -330,7 +330,7 @@ class RestClient: QuickSpec { var time: NSDate? client.time({ date, error in - time = date + time = date as NSDate? as NSDate? }) expect(time?.timeIntervalSince1970).toEventually(beCloseTo(NSDate().timeIntervalSince1970, within: 60), timeout: testTimeout) @@ -361,10 +361,10 @@ class RestClient: QuickSpec { } } - let requestUrlA = testHTTPExecutor.requests.first!.URL! + let requestUrlA = testHTTPExecutor.requests.first!.url! expect(requestUrlA.scheme).to(equal("https")) - let requestUrlB = testHTTPExecutor.requests.last!.URL! + let requestUrlB = testHTTPExecutor.requests.last!.url! expect(requestUrlB.scheme).to(equal("http")) } @@ -385,7 +385,7 @@ class RestClient: QuickSpec { waitUntil(timeout: testTimeout) { done in client.auth.authorize(nil, options: nil) { tokenDetails, error in if let e = error { - XCTFail(e.description) + XCTFail(e.localizedDescription) done() return } @@ -485,9 +485,9 @@ class RestClient: QuickSpec { tokenParams.ttl = 3.0 //Seconds waitUntil(timeout: testTimeout) { done in - auth.requestToken(tokenParams, withOptions: nil) { tokenDetails, error in + auth.requestToken(tokenParams, with: nil) { tokenDetails, error in if let e = error { - XCTFail(e.description) + XCTFail(e.localizedDescription) done() return } @@ -502,9 +502,9 @@ class RestClient: QuickSpec { options.key = client.options.key // Expired token - options.tokenDetails = ARTTokenDetails(token: currentTokenDetails.token, expires: currentTokenDetails.expires!.dateByAddingTimeInterval(testTimeout), issued: currentTokenDetails.issued, capability: currentTokenDetails.capability, clientId: currentTokenDetails.clientId) + options.tokenDetails = ARTTokenDetails(token: currentTokenDetails.token, expires: currentTokenDetails.expires!.addingTimeInterval(testTimeout), issued: currentTokenDetails.issued, capability: currentTokenDetails.capability, clientId: currentTokenDetails.clientId) - options.authUrl = NSURL(string: "http://test-auth.ably.io") + options.authUrl = NSURL(string: "http://test-auth.ably.io") as URL? let rest = ARTRest(options: options) rest.httpExecutor = testHTTPExecutor @@ -536,9 +536,9 @@ class RestClient: QuickSpec { tokenParams.ttl = 3.0 //Seconds waitUntil(timeout: testTimeout) { done in - auth.requestToken(tokenParams, withOptions: nil) { tokenDetails, error in + auth.requestToken(tokenParams, with: nil) { tokenDetails, error in if let e = error { - XCTFail(e.description) + XCTFail(e.localizedDescription) done() return } @@ -553,7 +553,7 @@ class RestClient: QuickSpec { options.key = client.options.key // Expired token - options.tokenDetails = ARTTokenDetails(token: currentTokenDetails.token, expires: currentTokenDetails.expires!.dateByAddingTimeInterval(testTimeout), issued: currentTokenDetails.issued, capability: currentTokenDetails.capability, clientId: currentTokenDetails.clientId) + options.tokenDetails = ARTTokenDetails(token: currentTokenDetails.token, expires: currentTokenDetails.expires!.addingTimeInterval(testTimeout), issued: currentTokenDetails.issued, capability: currentTokenDetails.capability, clientId: currentTokenDetails.clientId) let rest = ARTRest(options: options) rest.httpExecutor = testHTTPExecutor @@ -635,21 +635,13 @@ class RestClient: QuickSpec { expect{ options.fallbackHosts = [] }.toNot(raiseException()) - expect{ options.fallbackHostsUseDefault = true }.to( - raiseException { exception in - expect(exception.name).to(equal(ARTFallbackIncompatibleOptionsException)) - } - ) + expect{ options.fallbackHostsUseDefault = true }.to(raiseException(named: ARTFallbackIncompatibleOptionsException)) options.fallbackHosts = nil expect{ options.fallbackHostsUseDefault = true }.toNot(raiseException()) - expect { options.fallbackHosts = ["fake.ably.io"] }.to( - raiseException { exception in - expect(exception.name).to(equal(ARTFallbackIncompatibleOptionsException)) - } - ) + expect { options.fallbackHosts = ["fake.ably.io"] }.to(raiseException(named: ARTFallbackIncompatibleOptionsException)) } } @@ -660,7 +652,7 @@ class RestClient: QuickSpec { options.environment = "test" let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in @@ -678,12 +670,12 @@ class RestClient: QuickSpec { let options = ARTClientOptions(key: "xxxx:xxxx") let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") var capturedURLs = [String]() testHTTPExecutor.afterRequest = { request, callback in - capturedURLs.append(request.URL!.absoluteString!) + capturedURLs.append(request.url!.absoluteString) if testHTTPExecutor.requests.count == 2 { // Stop testHTTPExecutor.http = nil @@ -711,12 +703,12 @@ class RestClient: QuickSpec { options.fallbackHosts = ["f.ably-realtime.com", "g.ably-realtime.com", "h.ably-realtime.com", "i.ably-realtime.com", "j.ably-realtime.com"] let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") var capturedURLs = [String]() testHTTPExecutor.afterRequest = { request, callback in - capturedURLs.append(request.URL!.absoluteString!) + capturedURLs.append(request.url!.absoluteString) if testHTTPExecutor.requests.count == 2 { // Stop testHTTPExecutor.http = nil @@ -745,12 +737,12 @@ class RestClient: QuickSpec { options.fallbackHostsUseDefault = true let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") var capturedURLs = [String]() testHTTPExecutor.afterRequest = { request, callback in - capturedURLs.append(request.URL!.absoluteString!) + capturedURLs.append(request.url!.absoluteString) if testHTTPExecutor.requests.count == 2 { // Stop testHTTPExecutor.http = nil @@ -779,7 +771,7 @@ class RestClient: QuickSpec { options.fallbackHostsUseDefault = false let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in @@ -798,12 +790,12 @@ class RestClient: QuickSpec { options.fallbackHosts = [] //to test TO3k6 let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") var capturedURLs = [String]() testHTTPExecutor.afterRequest = { request, callback in - capturedURLs.append(request.URL!.absoluteString!) + capturedURLs.append(request.url!.absoluteString) } waitUntil(timeout: testTimeout) { done in @@ -822,12 +814,12 @@ class RestClient: QuickSpec { options.fallbackHosts = nil let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") var capturedURLs = [String]() testHTTPExecutor.afterRequest = { request, callback in - capturedURLs.append(request.URL!.absoluteString!) + capturedURLs.append(request.url!.absoluteString) if testHTTPExecutor.requests.count == 2 { // Stop testHTTPExecutor.http = nil @@ -855,7 +847,7 @@ class RestClient: QuickSpec { options.httpMaxRetryCount = 1 let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in @@ -877,9 +869,9 @@ class RestClient: QuickSpec { return } - expect(NSRegularExpression.match(testHTTPExecutor.requests[0].URL!.absoluteString, pattern: "//\(ARTDefault.restHost())")).to(beTrue()) - expect(NSRegularExpression.match(testHTTPExecutor.requests[1].URL!.absoluteString, pattern: "//[a-e].ably-realtime.com")).to(beTrue()) - expect(NSRegularExpression.match(testHTTPExecutor.requests[2].URL!.absoluteString, pattern: "//\(ARTDefault.restHost())")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[0].url!.absoluteString, pattern: "//\(ARTDefault.restHost())")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[1].url!.absoluteString, pattern: "//[a-e].ably-realtime.com")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[2].url!.absoluteString, pattern: "//\(ARTDefault.restHost())")).to(beTrue()) } // RSC15e @@ -889,7 +881,7 @@ class RestClient: QuickSpec { options.restHost = "fake.ably.io" let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) let channel = client.channels.get("test") waitUntil(timeout: testTimeout) { done in @@ -912,8 +904,8 @@ class RestClient: QuickSpec { } expect(client.options.restHost).to(equal("fake.ably.io")) - expect(NSRegularExpression.match(testHTTPExecutor.requests[0].URL!.absoluteString, pattern: "//\(client.options.restHost)")).to(beTrue()) - expect(NSRegularExpression.match(testHTTPExecutor.requests[1].URL!.absoluteString, pattern: "//\(client.options.restHost)")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[0].url!.absoluteString, pattern: "//\(client.options.restHost)")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[1].url!.absoluteString, pattern: "//\(client.options.restHost)")).to(beTrue()) } // RSC15a @@ -940,7 +932,7 @@ class RestClient: QuickSpec { it("default fallback hosts should match @[a-e].ably-realtime.com@") { let defaultFallbackHosts = ARTDefault.fallbackHosts() - defaultFallbackHosts.forEach { host in + defaultFallbackHosts?.forEach { host in expect(host).to(match("[a-e].ably-realtime.com")) } expect(defaultFallbackHosts).to(haveCount(5)) @@ -951,7 +943,7 @@ class RestClient: QuickSpec { let client = ARTRest(options: options) options.httpMaxRetryCount = 3 client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .HostUnreachable) + testHTTPExecutor.http = MockHTTP(network: .hostUnreachable) testHTTPExecutor.afterRequest = { _, _ in if testHTTPExecutor.requests.count > Int(1 + options.httpMaxRetryCount) { fail("Should not retry more than \(options.httpMaxRetryCount)") @@ -968,8 +960,8 @@ class RestClient: QuickSpec { expect(testHTTPExecutor.requests).to(haveCount(Int(1 + options.httpMaxRetryCount))) - let extractHostname = { (request: NSURLRequest) in - NSRegularExpression.extract(request.URL!.absoluteString, pattern: "[a-e].ably-realtime.com") + let extractHostname = { (request: URLRequest) in + NSRegularExpression.extract(request.url!.absoluteString, pattern: "[a-e].ably-realtime.com") } let resultFallbackHosts = testHTTPExecutor.requests.flatMap(extractHostname) let expectedFallbackHosts = Array(expectedHostOrder.map({ ARTDefault.fallbackHosts()[$0] })[0.. Int(1 + options.httpMaxRetryCount) { fail("Should not retry more than \(options.httpMaxRetryCount)") @@ -1060,8 +1052,8 @@ class RestClient: QuickSpec { expect(testHTTPExecutor.requests).to(haveCount(Int(1 + options.httpMaxRetryCount))) expect((testHTTPExecutor.requests.count) < (_fallbackHosts.count + 1)).to(beTrue()) - let extractHostname = { (request: NSURLRequest) in - NSRegularExpression.extract(request.URL!.absoluteString, pattern: "[f-j].ably-realtime.com") + let extractHostname = { (request: URLRequest) in + NSRegularExpression.extract(request.url!.absoluteString, pattern: "[f-j].ably-realtime.com") } let resultFallbackHosts = testHTTPExecutor.requests.flatMap(extractHostname) let expectedFallbackHosts = Array(expectedHostOrder.map({ _fallbackHosts[$0] })[0.. Int(1 + options.httpMaxRetryCount) { fail("Should not retry more than \(options.httpMaxRetryCount)") @@ -1119,16 +1111,16 @@ class RestClient: QuickSpec { } expect(testHTTPExecutor.requests).to(haveCount(1)) - expect(NSRegularExpression.match(testHTTPExecutor.requests[0].URL!.absoluteString, pattern: "//rest.ably.io")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[0].url!.absoluteString, pattern: "//rest.ably.io")).to(beTrue()) } } // RSC15d context("should use an alternative host when") { - for caseTest: NetworkAnswer in [.HostUnreachable, - .RequestTimeout(timeout: 0.1), - .HostInternalError(code: 501)] { + for caseTest: NetworkAnswer in [.hostUnreachable, + .requestTimeout(timeout: 0.1), + .hostInternalError(code: 501)] { it("\(caseTest)") { let options = ARTClientOptions(key: "xxxx:xxxx") let client = ARTRest(options: options) @@ -1154,8 +1146,8 @@ class RestClient: QuickSpec { if testHTTPExecutor.requests.count != 2 { return } - expect(NSRegularExpression.match(testHTTPExecutor.requests[0].URL!.absoluteString, pattern: "//rest.ably.io")).to(beTrue()) - expect(NSRegularExpression.match(testHTTPExecutor.requests[1].URL!.absoluteString, pattern: "//[a-e].ably-realtime.com")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[0].url!.absoluteString, pattern: "//rest.ably.io")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[1].url!.absoluteString, pattern: "//[a-e].ably-realtime.com")).to(beTrue()) } } } @@ -1165,7 +1157,7 @@ class RestClient: QuickSpec { let options = ARTClientOptions(key: "xxxx:xxxx") let client = ARTRest(options: options) client.httpExecutor = testHTTPExecutor - testHTTPExecutor.http = MockHTTP(network: .Host400BadRequest) + testHTTPExecutor.http = MockHTTP(network: .host400BadRequest) let channel = client.channels.get("test") testHTTPExecutor.afterRequest = { _ in @@ -1182,7 +1174,7 @@ class RestClient: QuickSpec { } expect(testHTTPExecutor.requests).to(haveCount(1)) - expect(NSRegularExpression.match(testHTTPExecutor.requests[0].URL!.absoluteString, pattern: "//rest.ably.io")).to(beTrue()) + expect(NSRegularExpression.match(testHTTPExecutor.requests[0].url!.absoluteString, pattern: "//rest.ably.io")).to(beTrue()) } } @@ -1200,7 +1192,7 @@ class RestClient: QuickSpec { } switch extractBodyAsMsgPack(testHTTPExecutor.requests.first) { - case .Failure(let error): + case .failure(let error): fail(error) default: break } @@ -1214,7 +1206,7 @@ class RestClient: QuickSpec { } let transport = realtime.transport as! TestProxyTransport - let object = AblyTests.msgpackToJSON(transport.rawDataSent.last!) + let object = AblyTests.msgpackToJSON(transport.rawDataSent.last! as NSData) expect(object["messages"][0]["data"].string).to(equal("message")) } @@ -1232,7 +1224,7 @@ class RestClient: QuickSpec { } switch extractBodyAsJSON(testHTTPExecutor.requests.first) { - case .Failure(let error): + case .failure(let error): fail(error) default: break } @@ -1246,8 +1238,8 @@ class RestClient: QuickSpec { } let transport = realtime.transport as! TestProxyTransport - let object = try! NSJSONSerialization.JSONObjectWithData(transport.rawDataSent.first!, options: NSJSONReadingOptions(rawValue: 0)) - expect(NSJSONSerialization.isValidJSONObject(object)).to(beTrue()) + let object = try! JSONSerialization.jsonObject(with: transport.rawDataSent.first!, options: JSONSerialization.ReadingOptions(rawValue: 0)) + expect(JSONSerialization.isValidJSONObject(object)).to(beTrue()) } // RSC7a @@ -1301,7 +1293,7 @@ class RestClient: QuickSpec { fail("Error is empty"); done() return } - expect(error.code).to(equal(Int(ARTState.RequestTokenFailed.rawValue))) + expect((error ).code).to(equal(Int(ARTState.requestTokenFailed.rawValue))) expect(error.message).to(contain("no means to renew the token is provided")) done() } @@ -1313,7 +1305,7 @@ class RestClient: QuickSpec { it("background behaviour") { let options = AblyTests.commonAppSetup() waitUntil(timeout: testTimeout) { done in - NSURLSession.sharedSession().dataTaskWithURL(NSURL(string:"https://ably.io")!) { _ in + URLSession.shared.dataTask(with: NSURL(string:"https://ably.io")! as URL) { _ in let rest = ARTRest(options: options) rest.channels.get("foo").history { _ in done() @@ -1324,9 +1316,9 @@ class RestClient: QuickSpec { // https://github.com/ably/ably-ios/issues/589 it("client should handle error messages in plaintext and HTML format") { - let request = NSURLRequest(URL: NSURL(string: "https://www.ably.io")!) + let request = NSURLRequest(url: NSURL(string: "https://www.ably.io")! as URL) waitUntil(timeout: testTimeout) { done in - ARTRest(key: "xxxx:xxxx").executeRequest(request, completion: { response, data, error in + ARTRest(key: "xxxx:xxxx").execute(request as URLRequest, completion: { response, data, error in guard let contentType = response?.allHeaderFields["Content-Type"] as? String else { fail("Response should have a Content-Type"); done(); return } @@ -1335,7 +1327,7 @@ class RestClient: QuickSpec { fail("Error is nil"); done(); return } expect(error.statusCode) == 200 - expect(error.message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) == 1000 + expect(error.message.lengthOfBytes(using: String.Encoding.utf8)) == 1000 done() }) } diff --git a/Spec/RestClientChannel.swift b/Spec/RestClientChannel.swift index 531ea8fce..57509bd4b 100644 --- a/Spec/RestClientChannel.swift +++ b/Spec/RestClientChannel.swift @@ -20,7 +20,7 @@ class RestClientChannel: QuickSpec { beforeEach { client = ARTRest(options: AblyTests.setupOptions(AblyTests.jsonRestOptions)) - channel = client.channels.get(NSProcessInfo.processInfo().globallyUniqueString) + channel = client.channels.get(ProcessInfo.processInfo.globallyUniqueString) testHTTPExecutor = TestProxyHTTPExecutor() } @@ -32,13 +32,13 @@ class RestClientChannel: QuickSpec { // RSL1b context("with name and data arguments") { it("publishes the message and invokes callback with success") { - var publishError: ARTErrorInfo? = ARTErrorInfo.createFromNSError(NSError(domain: "", code: -1, userInfo: nil)) + var publishError: ARTErrorInfo? = ARTErrorInfo.create(from: NSError(domain: "", code: -1, userInfo: nil)) var publishedMessage: ARTMessage? channel.publish(name, data: data) { error in publishError = error channel.history { result, _ in - publishedMessage = result?.items.first as? ARTMessage + publishedMessage = result?.items.first } } @@ -51,13 +51,13 @@ class RestClientChannel: QuickSpec { // RSL1b, RSL1e context("with name only") { it("publishes the message and invokes callback with success") { - var publishError: ARTErrorInfo? = ARTErrorInfo.createFromNSError(NSError(domain: "", code: -1, userInfo: nil)) + var publishError: ARTErrorInfo? = ARTErrorInfo.create(from: NSError(domain: "", code: -1, userInfo: nil)) var publishedMessage: ARTMessage? channel.publish(name, data: nil) { error in publishError = error channel.history { result, _ in - publishedMessage = result?.items.first as? ARTMessage + publishedMessage = result?.items.first } } @@ -70,13 +70,13 @@ class RestClientChannel: QuickSpec { // RSL1b, RSL1e context("with data only") { it("publishes the message and invokes callback with success") { - var publishError: ARTErrorInfo? = ARTErrorInfo.createFromNSError(NSError(domain: "", code: -1, userInfo: nil)) + var publishError: ARTErrorInfo? = ARTErrorInfo.create(from: NSError(domain: "", code: -1, userInfo: nil)) var publishedMessage: ARTMessage? channel.publish(nil, data: data) { error in publishError = error channel.history { result, _ in - publishedMessage = result?.items.first as? ARTMessage + publishedMessage = result?.items.first } } @@ -89,13 +89,13 @@ class RestClientChannel: QuickSpec { // RSL1b, RSL1e context("with neither name nor data") { it("publishes the message and invokes callback with success") { - var publishError: ARTErrorInfo? = ARTErrorInfo.createFromNSError(NSError(domain: "", code: -1, userInfo: nil)) + var publishError: ARTErrorInfo? = ARTErrorInfo.create(from: NSError(domain: "", code: -1, userInfo: nil)) var publishedMessage: ARTMessage? channel.publish(nil, data: nil) { error in publishError = error channel.history { result, _ in - publishedMessage = result?.items.first as? ARTMessage + publishedMessage = result?.items.first } } @@ -107,13 +107,13 @@ class RestClientChannel: QuickSpec { context("with a Message object") { it("publishes the message and invokes callback with success") { - var publishError: ARTErrorInfo? = ARTErrorInfo.createFromNSError(NSError(domain: "", code: -1, userInfo: nil)) + var publishError: ARTErrorInfo? = ARTErrorInfo.create(from: NSError(domain: "", code: -1, userInfo: nil)) var publishedMessage: ARTMessage? channel.publish([ARTMessage(name: name, data: data)]) { error in publishError = error channel.history { result, _ in - publishedMessage = result?.items.first as? ARTMessage + publishedMessage = result?.items.first } } @@ -130,7 +130,7 @@ class RestClientChannel: QuickSpec { defer { client.httpExecutor = oldExecutor} client.httpExecutor = testHTTPExecutor - var publishError: ARTErrorInfo? = ARTErrorInfo.createFromNSError(NSError(domain: "", code: -1, userInfo: nil)) + var publishError: ARTErrorInfo? = ARTErrorInfo.create(from: NSError(domain: "", code: -1, userInfo: nil)) var publishedMessages: [ARTMessage] = [] let messages = [ @@ -141,15 +141,15 @@ class RestClientChannel: QuickSpec { publishError = error client.httpExecutor = oldExecutor channel.history { result, _ in - if let items = result?.items as? [ARTMessage] { - publishedMessages.appendContentsOf(items) + if let items = result?.items { + publishedMessages.append(contentsOf:items) } } } expect(publishError).toEventually(beNil(), timeout: testTimeout) expect(publishedMessages.count).toEventually(equal(messages.count), timeout: testTimeout) - for (i, publishedMessage) in publishedMessages.reverse().enumerate() { + for (i, publishedMessage) in publishedMessages.reversed().enumerated() { expect(publishedMessage.data as? NSObject).to(equal(messages[i].data as? NSObject)) expect(publishedMessage.name).to(equal(messages[i].name)) } @@ -166,10 +166,10 @@ class RestClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.publish([ARTMessage(name: nil, data: "message", clientId: "tester")]) { error in expect(error).to(beNil()) - expect(client.auth.method).to(equal(ARTAuthMethod.Basic)) + expect(client.auth.method).to(equal(ARTAuthMethod.basic)) channel.history { page, error in expect(error).to(beNil()) - let item = page!.items[0] as! ARTMessage + let item = page!.items[0] expect(item.clientId).to(equal("tester")) done() } @@ -199,7 +199,7 @@ class RestClientChannel: QuickSpec { expect(error).to(beNil()) channel.history { page, error in expect(error).to(beNil()) - let item = page!.items[0] as! ARTMessage + let item = page!.items[0] expect(item.clientId).to(equal("john")) done() } @@ -222,7 +222,7 @@ class RestClientChannel: QuickSpec { expect(error).to(beNil()) channel.history { page, error in expect(error).to(beNil()) - let item = page!.items[0] as! ARTMessage + let item = page!.items[0] expect(item.clientId).to(equal("john")) done() } @@ -239,14 +239,14 @@ class RestClientChannel: QuickSpec { let channel = client.channels.get("test") // Reject before the message is sent to the server - let hook = channel.testSuite_injectIntoMethodBefore(#selector(ARTChannel.publish(_:callback:))) { + let hook = channel.testSuite_injectIntoMethod(before: #selector(ARTChannel.publish(_:callback:))) { testHTTPExecutor.http = nil } waitUntil(timeout: testTimeout) { done in let message = ARTMessage(name: nil, data: "message", clientId: "tester") channel.publish([message]) { error in - expect(error!.code).to(equal(Int(ARTState.MismatchedClientId.rawValue))) + expect(error!.code).to(equal(Int(ARTState.mismatchedClientId.rawValue))) done() } } @@ -272,14 +272,14 @@ class RestClientChannel: QuickSpec { let channel = client.channels.get("test") // Reject before the message is sent to the server - channel.testSuite_injectIntoMethodBefore(#selector(ARTChannel.publish(_:callback:))) { + channel.testSuite_injectIntoMethod(before: #selector(ARTChannel.publish(_:callback:))) { testHTTPExecutor.http = nil } waitUntil(timeout: testTimeout) { done in let message = ARTMessage(name: nil, data: "message", clientId: "tester") channel.publish([message]) { error in - expect(error!.code).to(equal(Int(ARTState.MismatchedClientId.rawValue))) + expect(error!.code).to(equal(Int(ARTState.mismatchedClientId.rawValue))) testHTTPExecutor.http = ARTHttp() channel.history { page, error in @@ -321,7 +321,7 @@ class RestClientChannel: QuickSpec { let channel = client.channels.get("test") let query = ARTDataQuery() - expect(query.direction) == ARTQueryDirection.Backwards + expect(query.direction) == ARTQueryDirection.backwards expect(query.limit) == 100 waitUntil(timeout: testTimeout) { done in @@ -361,7 +361,8 @@ class RestClientChannel: QuickSpec { } expect(result.hasNext).to(beFalse()) expect(result.isLast).to(beTrue()) - guard let items = result.items as? [ARTMessage] where result.items.count == 2 else { + let items = result.items + if items.count != 2 { fail("PaginatedResult has no items"); done() return } @@ -379,18 +380,18 @@ class RestClientChannel: QuickSpec { let channel = client.channels.get("test") let query = ARTDataQuery() - query.direction = .Backwards - query.end = NSDate() - query.start = query.end!.dateByAddingTimeInterval(10.0) + query.direction = .backwards + query.end = NSDate() as Date + query.start = query.end!.addingTimeInterval(10.0) - expect { try channel.history(query) { _, _ in } }.to(throwError { (error: ErrorType) in - expect(error._code).to(equal(ARTDataQueryError.TimestampRange.rawValue)) + expect { try channel.history(query) { _, _ in } }.to(throwError { (error: Error) in + expect(error._code).to(equal(ARTDataQueryError.timestampRange.rawValue)) }) - query.direction = .Forwards + query.direction = .forwards - expect { try channel.history(query) { _, _ in } }.to(throwError { (error: ErrorType) in - expect(error._code).to(equal(ARTDataQueryError.TimestampRange.rawValue)) + expect { try channel.history(query) { _, _ in } }.to(throwError { (error: Error) in + expect(error._code).to(equal(ARTDataQueryError.timestampRange.rawValue)) }) } @@ -400,8 +401,8 @@ class RestClientChannel: QuickSpec { let channel = client.channels.get("test") let query = ARTDataQuery() - expect(query.direction) == ARTQueryDirection.Backwards - query.direction = .Forwards + expect(query.direction) == ARTQueryDirection.backwards + query.direction = .forwards let messages = [ ARTMessage(name: nil, data: "message1"), @@ -422,7 +423,8 @@ class RestClientChannel: QuickSpec { } expect(result.hasNext).to(beFalse()) expect(result.isLast).to(beTrue()) - guard let items = result.items as? [ARTMessage] where result.items.count == 2 else { + let items = result.items + if items.count != 2 { fail("PaginatedResult has no items"); done() return } @@ -459,7 +461,8 @@ class RestClientChannel: QuickSpec { } expect(result.hasNext).to(beTrue()) expect(result.isLast).to(beFalse()) - guard let items = result.items as? [ARTMessage] where result.items.count == 2 else { + let items = result.items + if items.count != 2 { fail("PaginatedResult has no items"); done() return } @@ -504,15 +507,15 @@ class RestClientChannel: QuickSpec { let key = appSetupJson["cipher"]["key"].string! let cipherParams = ARTCipherParams.init( algorithm: appSetupJson["cipher"]["algorithm"].string!, - key: key, - iv: NSData(base64EncodedString: appSetupJson["cipher"]["iv"].string!, options: NSDataBase64DecodingOptions.init(rawValue: 0))! + key: key as ARTCipherKeyCompatible, + iv: NSData(base64Encoded: appSetupJson["cipher"]["iv"].string!, options: NSData.Base64DecodingOptions.init(rawValue: 0))! as Data ) let channel = client.channels.get("persisted:presence_fixtures", options:ARTChannelOptions.init(cipher: cipherParams)) var presenceMessages: [ARTPresenceMessage] = [] channel.presence.get() { result, _ in - if let items = result?.items as? [ARTPresenceMessage] { - presenceMessages.appendContentsOf(items) + if let items = result?.items { + presenceMessages.append(contentsOf:items) } } @@ -523,7 +526,7 @@ class RestClientChannel: QuickSpec { }).first!.1 expect(message.data).toNot(beNil()) - expect(message.action).to(equal(ARTPresenceAction.Present)) + expect(message.action).to(equal(ARTPresenceAction.present)) let encodedFixture = channel.dataEncoder.decode( fixtureMessage["data"].object, @@ -539,16 +542,16 @@ class RestClientChannel: QuickSpec { describe("message encoding") { struct TestCase { - let value: AnyObject? + let value: Any? let expected: JSON } let text = "John" let integer = "5" let decimal = "65.33" - let dictionary = ["number":3, "name":"John"] + let dictionary = ["number":3, "name":"John"] as [String : Any] let array = ["John", "Mary"] - let binaryData = NSString(string: "123456").dataUsingEncoding(NSUTF8StringEncoding)! + let binaryData = "123456".data(using: .utf8)! // RSL4a it("payloads should be binary, strings, or objects capable of JSON representation") { @@ -557,8 +560,8 @@ class RestClientChannel: QuickSpec { TestCase(value: text, expected: JSON(["data": text])), TestCase(value: integer, expected: JSON(["data": integer])), TestCase(value: decimal, expected: JSON(["data": decimal])), - TestCase(value: dictionary, expected: JSON(["data": JSON(dictionary).rawString(0, options: NSJSONWritingOptions.init(rawValue: 0))!, "encoding": "json"])), - TestCase(value: array, expected: JSON(["data": JSON(array).rawString(0, options: NSJSONWritingOptions.init(rawValue: 0))!, "encoding": "json"])), + TestCase(value: dictionary, expected: ["data": JSON(dictionary).rawString()!, "encoding": "json"] as JSON), + TestCase(value: array, expected: JSON(["data": JSON(array).rawString()!, "encoding": "json"])), TestCase(value: binaryData, expected: JSON(["data": binaryData.toBase64, "encoding": "base64"])), ] @@ -568,17 +571,17 @@ class RestClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.publish(nil, data: caseTest.value) { error in expect(error).to(beNil()) - guard let httpBody = testHTTPExecutor.requests.last!.HTTPBody else { + guard let httpBody = testHTTPExecutor.requests.last!.httpBody else { XCTFail("HTTPBody is nil"); done(); return } - expect(AblyTests.msgpackToJSON(httpBody)).to(equal(caseTest.expected)) + expect(AblyTests.msgpackToJSON(httpBody as NSData)).to(equal(caseTest.expected)) done() } } } - let invalidCases = [5, 56.33, NSDate()] + let invalidCases = [5, 56.33, NSDate()] as [Any] invalidCases.forEach { caseItem in waitUntil(timeout: testTimeout) { done in @@ -591,7 +594,7 @@ class RestClientChannel: QuickSpec { // RSL4b it("encoding attribute should represent the encoding(s) applied in right to left") { let encodingCases = [ - TestCase(value: text, expected: nil), + TestCase(value: text, expected: JSON.null), TestCase(value: dictionary, expected: "json"), TestCase(value: array, expected: "json"), TestCase(value: binaryData, expected: "base64"), @@ -603,11 +606,11 @@ class RestClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.publish(nil, data: caseItem.value, callback: { error in expect(error).to(beNil()) - guard let httpBody = testHTTPExecutor.requests.last!.HTTPBody else { + guard let httpBody = testHTTPExecutor.requests.last!.httpBody else { XCTFail("HTTPBody is nil"); done(); return } - expect(AblyTests.msgpackToJSON(httpBody)["encoding"]).to(equal(caseItem.expected)) + expect(AblyTests.msgpackToJSON(httpBody as NSData)["encoding"]).to(equal(caseItem.expected)) done() }) } @@ -621,12 +624,12 @@ class RestClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.publish(nil, data: binaryData, callback: { error in expect(error).to(beNil()) - guard let httpBody = testHTTPExecutor.requests.last!.HTTPBody else { + guard let httpBody = testHTTPExecutor.requests.last!.httpBody else { XCTFail("HTTPBody is nil"); done(); return } // Binary - let json = AblyTests.msgpackToJSON(httpBody) + let json = AblyTests.msgpackToJSON(httpBody as NSData) expect(json["data"].string).to(equal(binaryData.toBase64)) expect(json["encoding"]).to(equal("base64")) done() @@ -641,9 +644,9 @@ class RestClientChannel: QuickSpec { channel.publish(nil, data: text, callback: { error in expect(error).to(beNil()) - if let request = testHTTPExecutor.requests.last, let http = request.HTTPBody { + if let request = testHTTPExecutor.requests.last, let http = request.httpBody { // String (UTF-8) - let json = AblyTests.msgpackToJSON(http) + let json = AblyTests.msgpackToJSON(http as NSData) expect(json["data"].string).to(equal(text)) expect(json["encoding"].string).to(beNil()) } @@ -665,11 +668,10 @@ class RestClientChannel: QuickSpec { channel.publish(nil, data: array, callback: { error in expect(error).to(beNil()) - if let request = testHTTPExecutor.requests.last, let http = request.HTTPBody { + if let request = testHTTPExecutor.requests.last, let http = request.httpBody { // Array - let json = AblyTests.msgpackToJSON(http) - print(json.rawString()) - expect(JSON(data: json["data"].stringValue.dataUsingEncoding(NSUTF8StringEncoding)!).asArray).to(equal(array)) + let json = AblyTests.msgpackToJSON(http as NSData) + expect(JSON(data: json["data"].stringValue.data(using: String.Encoding.utf8)!).asArray).to(equal(array as NSArray?)) expect(json["encoding"].string).to(equal("json")) } else { @@ -687,10 +689,10 @@ class RestClientChannel: QuickSpec { channel.publish(nil, data: dictionary, callback: { error in expect(error).to(beNil()) - if let request = testHTTPExecutor.requests.last, let http = request.HTTPBody { + if let request = testHTTPExecutor.requests.last, let http = request.httpBody { // Dictionary - let json = AblyTests.msgpackToJSON(http) - expect(JSON(data: json["data"].stringValue.dataUsingEncoding(NSUTF8StringEncoding)!).asDictionary).to(equal(dictionary)) + let json = AblyTests.msgpackToJSON(http as NSData) + expect(JSON(data: json["data"].stringValue.data(using: String.Encoding.utf8)!).asDictionary).to(equal(dictionary as NSDictionary?)) expect(json["encoding"].string).to(equal("json")) } else { @@ -705,7 +707,7 @@ class RestClientChannel: QuickSpec { // RSL4d4 it("messages received should be decoded based on the encoding field") { - let cases = [text, integer, decimal, dictionary, array, binaryData] + let cases = [text, integer, decimal, dictionary, array, binaryData] as [Any] cases.forEach { caseTest in waitUntil(timeout: testTimeout) { done in @@ -725,21 +727,21 @@ class RestClientChannel: QuickSpec { } expect(result.hasNext).to(beFalse()) - for (index, item) in (result.items.reverse().enumerate()) { + for (index, item) in (result.items.reversed().enumerated()) { totalReceived += 1 - switch (item as? ARTMessage)?.data { + switch item.data { case let value as NSDictionary: - expect(value).to(equal(cases[index])) + expect(value).to(equal(cases[index] as? NSDictionary)) break case let value as NSArray: - expect(value).to(equal(cases[index])) + expect(value).to(equal(cases[index] as? NSArray)) break case let value as NSData: - expect(value).to(equal(cases[index])) + expect(value).to(equal(cases[index] as? NSData)) break case let value as NSString: - expect(value).to(equal(cases[index])) + expect(value).to(equal(cases[index] as? NSString)) break default: XCTFail("Payload with unknown format") @@ -781,11 +783,11 @@ class RestClientChannel: QuickSpec { } } - guard let httpBody = testHTTPExecutor.requests.last?.HTTPBody else { + guard let httpBody = testHTTPExecutor.requests.last?.httpBody else { fail("HTTPBody is empty") return } - let httpBodyAsJSON = AblyTests.msgpackToJSON(httpBody) + let httpBodyAsJSON = AblyTests.msgpackToJSON(httpBody as NSData) expect(httpBodyAsJSON["encoding"].string).to(equal("utf-8/cipher+aes-\(encryptionKeyLength)-cbc/base64")) expect(httpBodyAsJSON["name"].string).to(equal("test")) expect(httpBodyAsJSON["data"].string).toNot(equal("message1")) @@ -799,7 +801,8 @@ class RestClientChannel: QuickSpec { } expect(result.hasNext).to(beFalse()) expect(result.isLast).to(beTrue()) - guard let items = result.items as? [ARTMessage] where !result.items.isEmpty else { + let items = result.items + if result.items.isEmpty { fail("PaginatedResult has no items"); done() return } @@ -823,7 +826,7 @@ class RestClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() let clientEncrypted = ARTRest(options: options) - let channelOptions = ARTChannelOptions(cipher: ["key":ARTCrypto.generateRandomKey()]) + let channelOptions = ARTChannelOptions(cipher: ["key":ARTCrypto.generateRandomKey()] as ARTCipherParamsCompatible) let channelEncrypted = clientEncrypted.channels.get("test", options: channelOptions) let expectedMessage = ["something":1] @@ -839,7 +842,7 @@ class RestClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.history { result, error in - let message = (result!.items as! [ARTMessage])[0] + let message = (result!.items )[0] expect(message.data is NSData).to(beTrue()) expect(message.encoding).to(equal("json/utf-8/cipher+aes-256-cbc")) done() @@ -852,16 +855,16 @@ class RestClientChannel: QuickSpec { let options = AblyTests.commonAppSetup() options.logHandler = ARTLog(capturingOutput: true) let client = ARTRest(options: options) - let channelOptions = ARTChannelOptions(cipher: ["key":ARTCrypto.generateRandomKey()]) + let channelOptions = ARTChannelOptions(cipher: ["key":ARTCrypto.generateRandomKey()] as ARTCipherParamsCompatible) let channel = client.channels.get("test", options: channelOptions) client.httpExecutor = testHTTPExecutor let expectedMessage = ["something":1] - let expectedData = try! NSJSONSerialization.dataWithJSONObject(expectedMessage, options: NSJSONWritingOptions(rawValue: 0)) + let expectedData = try! JSONSerialization.data(withJSONObject: expectedMessage, options: JSONSerialization.WritingOptions(rawValue: 0)) testHTTPExecutor.beforeProcessingDataResponse = { data in - let dataStr = String(data: data!, encoding: NSUTF8StringEncoding)! - return dataStr.replace("json/utf-8", withString: "invalid").dataUsingEncoding(NSUTF8StringEncoding)! + let dataStr = String(data: data!, encoding: String.Encoding.utf8)! + return dataStr.replace("json/utf-8", withString: "invalid").data(using: String.Encoding.utf8)! } waitUntil(timeout: testTimeout) { done in @@ -872,8 +875,8 @@ class RestClientChannel: QuickSpec { waitUntil(timeout: testTimeout) { done in channel.history { result, error in - let message = (result!.items as! [ARTMessage])[0] - expect(message.data as? NSData).to(equal(expectedData)) + let message = (result!.items )[0] + expect(message.data as? NSData).to(equal(expectedData as NSData?)) expect(message.encoding).to(equal("invalid")) let logs = options.logHandler.captured diff --git a/Spec/RestClientChannels.swift b/Spec/RestClientChannels.swift index 20fe1d968..c828ab337 100644 --- a/Spec/RestClientChannels.swift +++ b/Spec/RestClientChannels.swift @@ -12,16 +12,16 @@ import Quick import Aspects // Swift isn't yet smart enough to do this automatically when bridging Objective-C APIs -extension ARTRestChannels: SequenceType { - public func generate() -> NSFastGenerator { - return NSFastGenerator(self) +extension ARTRestChannels: Sequence { + public func makeIterator() -> NSFastEnumerationIterator { + return NSFastEnumerationIterator(self) } } -private func beAChannel(named channelName: String) -> MatcherFunc { - return MatcherFunc { actualExpression, failureMessage in +private func beAChannel(named channelName: String) -> Predicate { + return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in let channel = try! actualExpression.evaluate() - failureMessage.expected = "expected \(channel)" + failureMessage.expected = "expected \(String(describing: channel))" failureMessage.postfixMessage = "be a channel" return channel?.name == channelName @@ -35,7 +35,7 @@ class RestClientChannels: QuickSpec { beforeEach { client = ARTRest(key: "fake:key") - channelName = NSProcessInfo.processInfo().globallyUniqueString + channelName = ProcessInfo.processInfo.globallyUniqueString } let cipherParams: ARTCipherParams? = nil @@ -123,11 +123,11 @@ class RestClientChannels: QuickSpec { it("should be enumerable") { let channels = [ client.channels.get(channelName), - client.channels.get(String(channelName.characters.reverse())) + client.channels.get(String(channelName.characters.reversed())) ] for channel in client.channels { - expect(channels).to(contain(channel)) + expect(channels).to(contain(channel as! [ARTRestChannel])) } } } diff --git a/Spec/RestClientPresence.swift b/Spec/RestClientPresence.swift index 773aa2f94..60c11fa32 100644 --- a/Spec/RestClientPresence.swift +++ b/Spec/RestClientPresence.swift @@ -35,7 +35,7 @@ class RestClientPresence: QuickSpec { let expectedPattern = "^user(\\d+)$" waitUntil(timeout: testTimeout) { done in // Load 150 members (2 pages) - disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 150, data:expectedData, options: options) { + disposable += [AblyTests.addMembersSequentiallyToChannel("test", members: 150, data:expectedData as AnyObject?, options: options) { done() }] } @@ -45,13 +45,13 @@ class RestClientPresence: QuickSpec { expect(error).to(beNil()) let membersPage = membersPage! - expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult)) + expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult.self)) expect(membersPage.items).to(haveCount(100)) - let members = membersPage.items as! [ARTPresenceMessage] + let members = membersPage.items expect(members).to(allPass({ member in return NSRegularExpression.match(member!.clientId, pattern: expectedPattern) - && (member!.data as? NSObject) == expectedData + && (member!.data as? String) == expectedData })) expect(membersPage.hasNext).to(beTrue()) @@ -60,13 +60,13 @@ class RestClientPresence: QuickSpec { membersPage.next { nextPage, error in expect(error).to(beNil()) let nextPage = nextPage! - expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult)) + expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult.self)) expect(nextPage.items).to(haveCount(50)) - let members = nextPage.items as! [ARTPresenceMessage] + let members = nextPage.items expect(members).to(allPass({ member in return NSRegularExpression.match(member!.clientId, pattern: expectedPattern) - && (member!.data as? NSObject) == expectedData + && (member!.data as? String) == expectedData })) expect(nextPage.hasNext).to(beFalse()) @@ -115,9 +115,9 @@ class RestClientPresence: QuickSpec { try! channel.presence.get(query) { membersPage, error in expect(error).to(beNil()) expect(membersPage!.items).to(haveCount(1)) - let member = membersPage!.items[0] as! ARTPresenceMessage + let member = membersPage!.items[0] expect(member.clientId).to(equal("john")) - expect(member.data as? NSObject).to(equal("web")) + expect(member.data as? NSObject).to(equal("web" as NSObject?)) done() } } @@ -162,7 +162,7 @@ class RestClientPresence: QuickSpec { expect(membersPage!.hasNext).to(beFalse()) expect(membersPage!.isLast).to(beTrue()) expect(membersPage!.items).to(allPass({ member in - let member = member as! ARTPresenceMessage + let member = member! return NSRegularExpression.match(member.clientId, pattern: "^user(7|8|9)") })) done() @@ -187,7 +187,7 @@ class RestClientPresence: QuickSpec { let expectedData = "online" let expectedPattern = "^user(\\d+)$" waitUntil(timeout: testTimeout) { done in - realtime = AblyTests.addMembersSequentiallyToChannel("test", members: 150, data: expectedData, options: options) { + realtime = AblyTests.addMembersSequentiallyToChannel("test", members: 150, data: expectedData as AnyObject?, options: options) { done() } } @@ -197,13 +197,13 @@ class RestClientPresence: QuickSpec { expect(error).to(beNil()) let membersPage = membersPage! - expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult)) + expect(membersPage).to(beAnInstanceOf(ARTPaginatedResult.self)) expect(membersPage.items).to(haveCount(100)) - let members = membersPage.items as! [ARTPresenceMessage] + let members = membersPage.items expect(members).to(allPass({ member in return NSRegularExpression.match(member!.clientId, pattern: expectedPattern) - && (member!.data as? NSObject) == expectedData + && (member!.data as? String) == expectedData })) expect(membersPage.hasNext).to(beTrue()) @@ -212,13 +212,13 @@ class RestClientPresence: QuickSpec { membersPage.next { nextPage, error in expect(error).to(beNil()) let nextPage = nextPage! - expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult)) + expect(nextPage).to(beAnInstanceOf(ARTPaginatedResult.self)) expect(nextPage.items).to(haveCount(50)) - let members = nextPage.items as! [ARTPresenceMessage] + let members = nextPage.items expect(members).to(allPass({ member in return NSRegularExpression.match(member!.clientId, pattern: expectedPattern) - && (member!.data as? NSObject) == expectedData + && (member!.data as? String) == expectedData })) expect(nextPage.hasNext).to(beFalse()) @@ -258,27 +258,27 @@ class RestClientPresence: QuickSpec { } let query = ARTDataQuery() - expect(query.direction).to(equal(ARTQueryDirection.Backwards)) + expect(query.direction).to(equal(ARTQueryDirection.backwards)) waitUntil(timeout: testTimeout) { done in try! channel.presence.history(query) { membersPage, error in expect(error).to(beNil()) - let firstMember = membersPage!.items.first as! ARTPresenceMessage + let firstMember = membersPage!.items.first! expect(firstMember.clientId).to(equal("user10")) - let lastMember = membersPage!.items.last as! ARTPresenceMessage + let lastMember = membersPage!.items.last! expect(lastMember.clientId).to(equal("user1")) done() } } - query.direction = .Forwards + query.direction = .forwards waitUntil(timeout: testTimeout) { done in try! channel.presence.history(query) { membersPage, error in expect(error).to(beNil()) - let firstMember = membersPage!.items.first as! ARTPresenceMessage + let firstMember = membersPage!.items.first! expect(firstMember.clientId).to(equal("user1")) - let lastMember = membersPage!.items.last as! ARTPresenceMessage + let lastMember = membersPage!.items.last! expect(lastMember.clientId).to(equal("user10")) done() } @@ -326,8 +326,8 @@ class RestClientPresence: QuickSpec { query.limit = 1001 - expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: ErrorType) in - expect(error._code).to(equal(ARTDataQueryError.Limit.rawValue)) + expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: Error) in + expect(error._code).to(equal(ARTDataQueryError.limit.rawValue)) }) } } @@ -371,7 +371,7 @@ class RestClientPresence: QuickSpec { expect(membersPage!.hasNext).to(beFalse()) expect(membersPage!.isLast).to(beTrue()) expect(membersPage!.items).to(allPass({ member in - let member = member as! ARTPresenceMessage? + let member = member return NSRegularExpression.match(member!.clientId, pattern: "^user(7|8|9)") })) done() @@ -456,18 +456,18 @@ class RestClientPresence: QuickSpec { let channel = client.channels.get("test") let query = ARTDataQuery() - query.direction = .Backwards - query.end = NSDate() - query.start = query.end!.dateByAddingTimeInterval(10.0) + query.direction = .backwards + query.end = NSDate() as Date + query.start = query.end!.addingTimeInterval(10.0) - expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: ErrorType) in - expect(error._code).to(equal(ARTDataQueryError.TimestampRange.rawValue)) + expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: Error) in + expect(error._code).to(equal(ARTDataQueryError.timestampRange.rawValue)) }) - query.direction = .Forwards + query.direction = .forwards - expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: ErrorType) in - expect(error._code).to(equal(ARTDataQueryError.TimestampRange.rawValue)) + expect { try channel.presence.history(query) { _, _ in } }.to(throwError { (error: Error) in + expect(error._code).to(equal(ARTDataQueryError.timestampRange.rawValue)) }) } @@ -502,17 +502,17 @@ class RestClientPresence: QuickSpec { } typealias Done = () -> Void - func checkReceivedMessage(done: Done) -> (ARTPaginatedResult?, ARTErrorInfo?) -> Void { + func checkReceivedMessage(_ done: @escaping Done) -> (ARTPaginatedResult?, ARTErrorInfo?) -> Void { return { membersPage, error in expect(error).to(beNil()) - let member = membersPage!.items[0] as! ARTBaseMessage - expect(member.data as? NSDictionary).to(equal(expectedData)) + let member = membersPage!.items[0] + expect(member.data as? NSDictionary).to(equal(expectedData as NSDictionary?)) done() } } var decodeNumberOfCalls = 0 - let hook = ARTBaseMessage.testSuite_injectIntoClassMethod(#selector(ARTBaseMessage.decodeWithEncoder(_:error:))) { + let hook = ARTBaseMessage.testSuite_injectIntoClassMethod(#selector(ARTBaseMessage.decode)) { decodeNumberOfCalls += 1 } defer { hook?.remove() } diff --git a/Spec/RestClientStats.swift b/Spec/RestClientStats.swift index c6fc0d33e..0790bcea5 100644 --- a/Spec/RestClientStats.swift +++ b/Spec/RestClientStats.swift @@ -12,15 +12,15 @@ import Quick import SwiftyJSON import Foundation -private func postTestStats(stats: JSON) -> ARTClientOptions { +private func postTestStats(_ stats: JSON) -> ARTClientOptions { let options = AblyTests.setupOptions(AblyTests.jsonRestOptions, forceNewApp: true); let keyBase64 = encodeBase64(options.key ?? "") - let request = NSMutableURLRequest(URL: NSURL(string: "\(AblyTests.clientOptions().restUrl().absoluteString!)/stats")!) + let request = NSMutableURLRequest(url: URL(string: "\(AblyTests.clientOptions().restUrl().absoluteString)/stats")!) - request.HTTPMethod = "POST" - request.HTTPBody = try? stats.rawData() + request.httpMethod = "POST" + request.httpBody = try? stats.rawData() request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("Basic \(keyBase64)", forHTTPHeaderField: "Authorization") @@ -37,18 +37,18 @@ private func postTestStats(stats: JSON) -> ARTClientOptions { return options } -private func queryStats(client: ARTRest, _ query: ARTStatsQuery) -> ARTPaginatedResult { - var stats: ARTPaginatedResult? +private func queryStats(_ client: ARTRest, _ query: ARTStatsQuery) -> ARTPaginatedResult { + var stats: ARTPaginatedResult? let dummyError = ARTErrorInfo() var error: ARTErrorInfo? = dummyError try! client.stats(query, callback: { result, err in - stats = result + stats = result as! ARTPaginatedResult? error = err }) while error === dummyError { - CFRunLoopRunInMode(kCFRunLoopDefaultMode, CFTimeInterval(0.1), Bool(0)) + CFRunLoopRunInMode(CFRunLoopMode.defaultMode, CFTimeInterval(0.1), Bool(0)) } if let error = error { @@ -58,8 +58,8 @@ private func queryStats(client: ARTRest, _ query: ARTStatsQuery) -> ARTPaginated return stats! } -private func getPage(paginator: ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) -> ARTPaginatedResult { - var newResult: ARTPaginatedResult? +private func getPage(_ paginator: ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) -> ARTPaginatedResult { + var newResult: ARTPaginatedResult? let dummyError = ARTErrorInfo() var error: ARTErrorInfo? = dummyError paginator({ paginatorResult, err in @@ -68,7 +68,7 @@ private func getPage(paginator: ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) - }) while error === dummyError { - CFRunLoopRunInMode(kCFRunLoopDefaultMode, CFTimeInterval(0.1), Bool(0)) + CFRunLoopRunInMode(CFRunLoopMode.defaultMode, CFTimeInterval(0.1), Bool(0)) } if let error = error { @@ -85,31 +85,31 @@ class RestClientStats: QuickSpec { context("stats") { // RSC6a context("result") { - let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! + let calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian)! let dateComponents = NSDateComponents() - dateComponents.year = calendar.component(NSCalendarUnit.Year, fromDate: NSDate()) - 1 + dateComponents.year = calendar.component(NSCalendar.Unit.year, from: NSDate() as Date) - 1 dateComponents.month = 2 dateComponents.day = 3 dateComponents.hour = 16 dateComponents.minute = 3 - let date = calendar.dateFromComponents(dateComponents)! - let dateFormatter = NSDateFormatter() - dateFormatter.timeZone = NSTimeZone(name: "UTC") + let date = calendar.date(from: dateComponents as DateComponents)! + let dateFormatter = DateFormatter() + dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone! dateFormatter.dateFormat = "YYYY-MM-dd:HH:mm" let statsFixtures: JSON = [ [ - "intervalId": dateFormatter.stringFromDate(date), // 20XX-02-03:16:03 + "intervalId": dateFormatter.string(from: date), // 20XX-02-03:16:03 "inbound": [ "realtime": [ "messages": [ "count": 50, "data": 5000 ] ] ], "outbound": [ "realtime": [ "messages": [ "count": 20, "data": 2000 ] ] ] ], [ - "intervalId": dateFormatter.stringFromDate(date.dateByAddingTimeInterval(60)), // 20XX-02-03:16:04 + "intervalId": dateFormatter.string(from: date.addingTimeInterval(60)), // 20XX-02-03:16:04 "inbound": [ "realtime": [ "messages": [ "count": 60, "data": 6000 ] ] ], "outbound": [ "realtime": [ "messages": [ "count": 10, "data": 1000 ] ] ] ], [ - "intervalId": dateFormatter.stringFromDate(date.dateByAddingTimeInterval(120)), // 20XX-02-03:16:05 + "intervalId": dateFormatter.string(from: date.addingTimeInterval(120)), // 20XX-02-03:16:05 "inbound": [ "realtime": [ "messages": [ "count": 70, "data": 7000 ] ] ], "outbound": [ "realtime": [ "messages": [ "count": 40, "data": 4000 ] ] ], "persisted": [ "presence": [ "count": 20, "data": 2000 ] ], @@ -130,12 +130,12 @@ class RestClientStats: QuickSpec { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() query.start = date - query.direction = .Forwards + query.direction = .forwards let result = queryStats(client, query) expect(result.items.count).to(equal(3)) - let totalInbound = result.items.reduce(0 as UInt, combine: { + let totalInbound = result.items.reduce(0 as UInt, { if let stats = $1 as? ARTStats { return $0 + stats.inbound.all.messages.count } @@ -143,7 +143,7 @@ class RestClientStats: QuickSpec { }) expect(totalInbound).to(equal(50 + 60 + 70)) - let totalOutbound = result.items.reduce(0 as UInt, combine: { + let totalOutbound = result.items.reduce(0 as UInt, { if let stats = $1 as? ARTStats { return $0 + stats.outbound.all.messages.count } @@ -156,17 +156,17 @@ class RestClientStats: QuickSpec { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() query.start = date - query.direction = .Forwards - query.unit = .Hour + query.direction = .forwards + query.unit = .hour let result = queryStats(client, query) - let totalInbound = result.items.reduce(0 as UInt, combine: { + let totalInbound = result.items.reduce(0 as UInt, { if let stats = $1 as? ARTStats { return $0 + stats.inbound.all.messages.count } return $0 }) - let totalOutbound = result.items.reduce(0 as UInt, combine: { + let totalOutbound = result.items.reduce(0 as UInt, { if let stats = $1 as? ARTStats { return $0 + stats.outbound.all.messages.count } @@ -181,13 +181,13 @@ class RestClientStats: QuickSpec { it("should match day-level inbound and outbound fixture data (forwards)") { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() - query.end = calendar.dateByAddingUnit(.Day, value: 1, toDate: date, options: NSCalendarOptions(rawValue: 0)) - query.direction = .Forwards - query.unit = .Month + query.end = calendar.date(byAdding: .day, value: 1, to: date, options: NSCalendar.Options(rawValue: 0)) + query.direction = .forwards + query.unit = .month let result = queryStats(client, query) - let totalInbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.inbound.all.messages.count }) - let totalOutbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.outbound.all.messages.count }) + let totalInbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.inbound.all.messages.count }) + let totalOutbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.outbound.all.messages.count }) expect(result.items.count).to(equal(1)) expect(totalInbound).to(equal(50 + 60 + 70)) @@ -197,13 +197,13 @@ class RestClientStats: QuickSpec { it("should match month-level inbound and outbound fixture data (forwards)") { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() - query.end = calendar.dateByAddingUnit(.Month, value: 1, toDate: date, options: NSCalendarOptions(rawValue: 0)) - query.direction = .Forwards - query.unit = .Month + query.end = calendar.date(byAdding: .month, value: 1, to: date, options: NSCalendar.Options(rawValue: 0)) + query.direction = .forwards + query.unit = .month let result = queryStats(client, query) - let totalInbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.inbound.all.messages.count }) - let totalOutbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.outbound.all.messages.count }) + let totalInbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.inbound.all.messages.count }) + let totalOutbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.outbound.all.messages.count }) expect(result.items.count).to(equal(1)) expect(totalInbound).to(equal(50 + 60 + 70)) @@ -213,12 +213,12 @@ class RestClientStats: QuickSpec { it("should contain only one item when limit is 1 (backwards") { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() - query.end = date.dateByAddingTimeInterval(60) // 20XX-02-03:16:04 + query.end = date.addingTimeInterval(60) // 20XX-02-03:16:04 query.limit = 1 let result = queryStats(client, query) - let totalInbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.inbound.all.messages.count }) - let totalOutbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.outbound.all.messages.count }) + let totalInbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.inbound.all.messages.count }) + let totalOutbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.outbound.all.messages.count }) expect(result.items.count).to(equal(1)) expect(totalInbound).to(equal(60)) @@ -228,13 +228,13 @@ class RestClientStats: QuickSpec { it("should contain only one item when limit is 1 (forwards") { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() - query.end = date.dateByAddingTimeInterval(60) // 20XX-02-03:16:04 + query.end = date.addingTimeInterval(60) // 20XX-02-03:16:04 query.limit = 1 - query.direction = .Forwards + query.direction = .forwards let result = queryStats(client, query) - let totalInbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.inbound.all.messages.count }) - let totalOutbound = (result.items as! [ARTStats]).reduce(0, combine: { $0 + $1.outbound.all.messages.count }) + let totalInbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.inbound.all.messages.count }) + let totalOutbound = (result.items as! [ARTStats]).reduce(0, { $0 + $1.outbound.all.messages.count }) expect(result.items.count).to(equal(1)) expect(totalInbound).to(equal(50)) @@ -244,7 +244,7 @@ class RestClientStats: QuickSpec { it("should be paginated according to the limit (backwards") { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() - query.end = date.dateByAddingTimeInterval(120) // 20XX-02-03:16:05 + query.end = date.addingTimeInterval(120) // 20XX-02-03:16:05 query.limit = 1 let firstPage = queryStats(client, query) @@ -253,18 +253,18 @@ class RestClientStats: QuickSpec { expect(firstPage.hasNext).to(beTrue()) expect(firstPage.isLast).to(beFalse()) - let secondPage = getPage(firstPage.next) + let secondPage = getPage(firstPage.next as! ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) expect(secondPage.items.count).to(equal(1)) expect((secondPage.items as! [ARTStats])[0].inbound.all.messages.data).to(equal(6000)) expect(secondPage.hasNext).to(beTrue()) expect(secondPage.isLast).to(beFalse()) - let thirdPage = getPage(secondPage.next) + let thirdPage = getPage(secondPage.next as! ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) expect(thirdPage.items.count).to(equal(1)) expect((thirdPage.items as! [ARTStats])[0].inbound.all.messages.data).to(equal(5000)) expect(thirdPage.isLast).to(beTrue()) - let firstPageAgain = getPage(thirdPage.first) + let firstPageAgain = getPage(thirdPage.first as! ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) expect(firstPageAgain.items.count).to(equal(1)) expect((firstPageAgain.items as! [ARTStats])[0].inbound.all.messages.data).to(equal(7000)) } @@ -272,9 +272,9 @@ class RestClientStats: QuickSpec { it("should be paginated according to the limit (fowards)") { let client = ARTRest(options: statsOptions) let query = ARTStatsQuery() - query.end = date.dateByAddingTimeInterval(120) // 20XX-02-03:16:05 + query.end = date.addingTimeInterval(120) // 20XX-02-03:16:05 query.limit = 1 - query.direction = .Forwards + query.direction = .forwards let firstPage = queryStats(client, query) expect(firstPage.items.count).to(equal(1)) @@ -282,18 +282,18 @@ class RestClientStats: QuickSpec { expect(firstPage.hasNext).to(beTrue()) expect(firstPage.isLast).to(beFalse()) - let secondPage = getPage(firstPage.next) + let secondPage = getPage(firstPage.next as! ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) expect(secondPage.items.count).to(equal(1)) expect((secondPage.items as! [ARTStats])[0].inbound.all.messages.data).to(equal(6000)) expect(secondPage.hasNext).to(beTrue()) expect(secondPage.isLast).to(beFalse()) - let thirdPage = getPage(secondPage.next) + let thirdPage = getPage(secondPage.next as! ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) expect(thirdPage.items.count).to(equal(1)) expect((thirdPage.items as! [ARTStats])[0].inbound.all.messages.data).to(equal(7000)) expect(thirdPage.isLast).to(beTrue()) - let firstPageAgain = getPage(thirdPage.first) + let firstPageAgain = getPage(thirdPage.first as! ((ARTPaginatedResult?, ARTErrorInfo?) -> Void) -> Void) expect(firstPageAgain.items.count).to(equal(1)) expect((firstPageAgain.items as! [ARTStats])[0].inbound.all.messages.data).to(equal(5000)) } @@ -307,8 +307,8 @@ class RestClientStats: QuickSpec { let client = ARTRest(key: "fake:key") let query = ARTStatsQuery() - query.start = NSDate.distantFuture() - query.end = NSDate.distantPast() + query.start = NSDate.distantFuture + query.end = NSDate.distantPast expect{try client.stats(query, callback:{ status, result in })}.to(throwError()) } @@ -319,7 +319,7 @@ class RestClientStats: QuickSpec { it("should be backwards by default") { let query = ARTStatsQuery() - expect(query.direction).to(equal(ARTQueryDirection.Backwards)); + expect(query.direction).to(equal(ARTQueryDirection.backwards)); } } @@ -346,7 +346,7 @@ class RestClientStats: QuickSpec { it("should default to minute") { let query = ARTStatsQuery() - expect(query.unit).to(equal(ARTStatsGranularity.Minute)) + expect(query.unit).to(equal(ARTStatsGranularity.minute)) } } } diff --git a/Spec/Stats.swift b/Spec/Stats.swift index 56ee5700e..f36eafc1d 100644 --- a/Spec/Stats.swift +++ b/Spec/Stats.swift @@ -26,7 +26,7 @@ class Stats: QuickSpec { ] let rawData = try! data.rawData() let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats - let subject = stats?.valueForKey(attribute) as? ARTStatsMessageTypes + let subject = stats?.value(forKey: attribute) as? ARTStatsMessageTypes it("should return a MessagesTypes object") { expect(subject).to(beAnInstanceOf(ARTStatsMessageTypes)) @@ -60,7 +60,7 @@ class Stats: QuickSpec { ] let rawData = try! data.rawData() let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats - let subject = stats?.valueForKey(direction) as? ARTStatsMessageTraffic + let subject = stats?.value(forKey: direction) as? ARTStatsMessageTraffic it("should return a MessageTraffic object") { expect(subject).to(beAnInstanceOf(ARTStatsMessageTraffic)) @@ -139,7 +139,7 @@ class Stats: QuickSpec { ] let rawData = try! data.rawData() let stats = try! encoder.decodeStats(rawData)[0] as? ARTStats - let subject = stats?.valueForKey(requestType) as? ARTStatsRequestCount + let subject = stats?.value(forKey: requestType) as? ARTStatsRequestCount context(requestType) { it("should return a RequestCount object") { @@ -170,9 +170,9 @@ class Stats: QuickSpec { dateComponents.day = 1 dateComponents.hour = 5 dateComponents.minute = 6 - dateComponents.timeZone = NSTimeZone(name: "UTC") + dateComponents.timeZone = NSTimeZone(name: "UTC") as TimeZone? - let expected = NSCalendar(identifier: NSCalendarIdentifierGregorian)?.dateFromComponents(dateComponents) + let expected = NSCalendar(identifier: NSCalendar.Identifier.gregorian)?.date(from: dateComponents as DateComponents) expect(stats?.intervalTime()).to(equal(expected)) } diff --git a/Spec/TestUtilities.swift b/Spec/TestUtilities.swift index e0a6f4052..31f8f6c81 100644 --- a/Spec/TestUtilities.swift +++ b/Spec/TestUtilities.swift @@ -27,46 +27,46 @@ enum CryptoTest: String { } class Configuration : QuickConfiguration { - override class func configure(configuration: Quick.Configuration!) { + override class func configure(_ configuration: Quick.Configuration!) { configuration.beforeSuite { AsyncDefaults.Timeout = testTimeout } } } -func pathForTestResource(resourcePath: String) -> String { - let testBundle = NSBundle(forClass: AblyTests.self) - return testBundle.pathForResource(resourcePath, ofType: "")! +func pathForTestResource(_ resourcePath: String) -> String { + let testBundle = Bundle(for: AblyTests.self) + return testBundle.path(forResource: resourcePath, ofType: "")! } -let appSetupJson = JSON(data: NSData(contentsOfFile: pathForTestResource(testResourcesPath + "test-app-setup.json"))!, options: .MutableContainers) +let appSetupJson = JSON(parseJSON: try! String(contentsOfFile: pathForTestResource(testResourcesPath + "test-app-setup.json"))) -let testTimeout: NSTimeInterval = 10.0 +let testTimeout: TimeInterval = 10.0 let testResourcesPath = "ably-common/test-resources/" /// Common test utilities. class AblyTests { - class func base64ToData(base64: String) -> NSData { - return NSData(base64EncodedString: base64, options: NSDataBase64DecodingOptions(rawValue: 0))! + class func base64ToData(_ base64: String) -> Data { + return Data(base64Encoded: base64, options: NSData.Base64DecodingOptions(rawValue: 0))! } - class func msgpackToJSON(data: NSData) -> JSON { - let decoded = try! ARTMsgPackEncoder().decode(data) + class func msgpackToJSON(_ data: NSData) -> JSON { + let decoded = try! ARTMsgPackEncoder().decode(data as Data) let encoded = try! ARTJsonEncoder().encode(decoded) return JSON(data: encoded) } - class func checkError(errorInfo: ARTErrorInfo?, withAlternative message: String) { + class func checkError(_ errorInfo: ARTErrorInfo?, withAlternative message: String) { if let error = errorInfo { - XCTFail("\(error.code): \(error.message)") + XCTFail("\((error ).code): \(error.message)") } else if !message.isEmpty { XCTFail(message) } } - class func checkError(errorInfo: ARTErrorInfo?) { + class func checkError(_ errorInfo: ARTErrorInfo?) { checkError(errorInfo, withAlternative: "") } @@ -80,7 +80,7 @@ class AblyTests { class var authTokenCases: [String: (ARTAuthOptions) -> ()] { get { return [ "useTokenAuth": { $0.useTokenAuth = true; $0.key = "fake:key" }, - "authUrl": { $0.authUrl = NSURL(string: "http://test.com") }, + "authUrl": { $0.authUrl = URL(string: "http://test.com") }, "authCallback": { $0.authCallback = { _, _ in return } }, "tokenDetails": { $0.tokenDetails = ARTTokenDetails(token: "token") }, "token": { $0.token = "token" }, @@ -90,9 +90,9 @@ class AblyTests { } static var testApplication: JSON? - static private var setupOptionsCounter = 0 + static fileprivate var setupOptionsCounter = 0 - class func setupOptions(options: ARTClientOptions, forceNewApp: Bool = false, debug: Bool = false) -> ARTClientOptions { + class func setupOptions(_ options: ARTClientOptions, forceNewApp: Bool = false, debug: Bool = false) -> ARTClientOptions { ARTChannels_getChannelNamePrefix = { "test-\(setupOptionsCounter)" } setupOptionsCounter += 1 @@ -101,9 +101,9 @@ class AblyTests { } guard let app = testApplication else { - let request = NSMutableURLRequest(URL: NSURL(string: "https://\(options.restHost):\(options.tlsPort)/apps")!) - request.HTTPMethod = "POST" - request.HTTPBody = try? appSetupJson["post_apps"].rawData() + let request = NSMutableURLRequest(url: URL(string: "https://\(options.restHost):\(options.tlsPort)/apps")!) + request.httpMethod = "POST" + request.httpBody = try? appSetupJson["post_apps"].rawData() request.allHTTPHeaderFields = [ "Accept" : "application/json", @@ -119,7 +119,7 @@ class AblyTests { testApplication = JSON(data: responseData!) if debug { - options.logLevel = .Verbose + options.logLevel = .verbose print(testApplication!) } @@ -131,18 +131,18 @@ class AblyTests { return options } - class func commonAppSetup(debug debug: Bool = false) -> ARTClientOptions { + class func commonAppSetup(_ debug: Bool = false) -> ARTClientOptions { return AblyTests.setupOptions(AblyTests.jsonRestOptions, debug: debug) } - class func clientOptions(debug debug: Bool = false, key: String? = nil, requestToken: Bool = false) -> ARTClientOptions { + class func clientOptions(_ debug: Bool = false, key: String? = nil, requestToken: Bool = false) -> ARTClientOptions { let options = ARTClientOptions() options.environment = "sandbox" if debug { - options.logLevel = .Debug + options.logLevel = .debug } else { - options.logLevel = .Info + options.logLevel = .info } if let key = key { options.key = key @@ -155,29 +155,29 @@ class AblyTests { class func newErrorProtocolMessage() -> ARTProtocolMessage { let protocolMessage = ARTProtocolMessage() - protocolMessage.action = .Error - protocolMessage.error = ARTErrorInfo.createWithCode(0, message: "Fail test") + protocolMessage.action = .error + protocolMessage.error = ARTErrorInfo.create(withCode: 0, message: "Fail test") return protocolMessage } - class func newPresenceProtocolMessage(channel: String, action: ARTPresenceAction, clientId: String) -> ARTProtocolMessage { + class func newPresenceProtocolMessage(_ channel: String, action: ARTPresenceAction, clientId: String) -> ARTProtocolMessage { let protocolMessage = ARTProtocolMessage() - protocolMessage.action = .Presence + protocolMessage.action = .presence protocolMessage.channel = channel - protocolMessage.timestamp = NSDate() + protocolMessage.timestamp = Date() let presenceMessage = ARTPresenceMessage() presenceMessage.action = action presenceMessage.clientId = clientId - presenceMessage.timestamp = NSDate() + presenceMessage.timestamp = Date() protocolMessage.presence = [presenceMessage] return protocolMessage } - class func newRealtime(options: ARTClientOptions) -> ARTRealtime { + class func newRealtime(_ options: ARTClientOptions) -> ARTRealtime { let autoConnect = options.autoConnect options.autoConnect = false let realtime = ARTRealtime(options: options) - realtime.setTransportClass(TestProxyTransport.self) + realtime.setTransport(TestProxyTransport.self) realtime.setReachabilityClass(TestReachability.self) if autoConnect { options.autoConnect = true @@ -187,10 +187,10 @@ class AblyTests { } class func newRandomString() -> String { - return NSProcessInfo.processInfo().globallyUniqueString + return ProcessInfo.processInfo.globallyUniqueString } - class func addMembersSequentiallyToChannel(channelName: String, members: Int = 1, startFrom: Int = 1, data: AnyObject? = nil, options: ARTClientOptions, done: ()->()) -> ARTRealtime { + class func addMembersSequentiallyToChannel(_ channelName: String, members: Int = 1, startFrom: Int = 1, data: AnyObject? = nil, options: ARTClientOptions, done: @escaping ()->()) -> ARTRealtime { let client = ARTRealtime(options: options) let channel = client.channels.get(channelName) @@ -213,7 +213,7 @@ class AblyTests { return client } - class func splitDone(howMany: Int, file: StaticString = #file, line: UInt = #line, done: () -> Void) -> (() -> Void) { + class func splitDone(_ howMany: Int, file: StaticString = #file, line: UInt = #line, done: @escaping () -> Void) -> (() -> Void) { var left = howMany return { left -= 1 @@ -247,71 +247,71 @@ class AblyTests { } - class func loadCryptoTestData(file: String) -> (key: NSData, iv: NSData, items: [CryptoTestItem]) { - let json = JSON(data: NSData(contentsOfFile: pathForTestResource(file))!) + class func loadCryptoTestData(_ file: String) -> (key: Data, iv: Data, items: [CryptoTestItem]) { + let json = JSON(parseJSON: try! String(contentsOfFile: pathForTestResource(file))) - let keyData = NSData(base64EncodedString: json["key"].stringValue, options: NSDataBase64DecodingOptions(rawValue: 0))! - let ivData = NSData(base64EncodedString: json["iv"].stringValue, options: NSDataBase64DecodingOptions(rawValue: 0))! + let keyData = Data(base64Encoded: json["key"].stringValue, options: Data.Base64DecodingOptions(rawValue: 0))! + let ivData = Data(base64Encoded: json["iv"].stringValue, options: Data.Base64DecodingOptions(rawValue: 0))! let items = json["items"].map{ $0.1 }.map(CryptoTestItem.init) return (keyData, ivData, items) } - class func loadCryptoTestData(crypto: CryptoTest) -> (key: NSData, iv: NSData, items: [CryptoTestItem]) { + class func loadCryptoTestData(_ crypto: CryptoTest) -> (key: Data, iv: Data, items: [CryptoTestItem]) { return loadCryptoTestData(testResourcesPath + crypto.rawValue + ".json") } } -class NSURLSessionServerTrustSync: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate { +class NSURLSessionServerTrustSync: NSObject, URLSessionDelegate, URLSessionTaskDelegate { - func get(request: NSMutableURLRequest) -> (NSData?, NSError?, NSHTTPURLResponse?) { + func get(_ request: NSMutableURLRequest) -> (Data?, NSError?, HTTPURLResponse?) { var responseError: NSError? - var responseData: NSData? - var httpResponse: NSHTTPURLResponse?; + var responseData: Data? + var httpResponse: HTTPURLResponse?; var requestCompleted = false - let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() - let session = NSURLSession(configuration:configuration, delegate:self, delegateQueue:NSOperationQueue.mainQueue()) + let configuration = URLSessionConfiguration.default + let session = Foundation.URLSession(configuration:configuration, delegate:self, delegateQueue:OperationQueue.main) - let task = session.dataTaskWithRequest(request) { data, response, error in - if let response = response as? NSHTTPURLResponse { + let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in + if let response = response as? HTTPURLResponse { responseData = data - responseError = error + responseError = error as NSError? httpResponse = response } else if let error = error { - responseError = error + responseError = error as NSError? } requestCompleted = true - } + }) task.resume() while !requestCompleted { - CFRunLoopRunInMode(kCFRunLoopDefaultMode, CFTimeInterval(0.1), Bool(0)) + CFRunLoopRunInMode(CFRunLoopMode.defaultMode, CFTimeInterval(0.1), Bool(0)) } return (responseData, responseError, httpResponse) } - func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // Try to extract the server certificate for trust validation if let serverTrust = challenge.protectionSpace.serverTrust { // Server trust authentication // Reference: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html - completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: serverTrust)) + completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust)) } else { - challenge.sender?.performDefaultHandlingForAuthenticationChallenge?(challenge) + challenge.sender?.performDefaultHandling?(for: challenge) XCTFail("Current authentication: \(challenge.protectionSpace.authenticationMethod)") } } } -extension NSDate { - func isBefore(other: NSDate) -> Bool { - return self.compare(other) == NSComparisonResult.OrderedAscending +extension Date { + func isBefore(_ other: Date) -> Bool { + return self.compare(other) == ComparisonResult.orderedAscending } } @@ -329,7 +329,7 @@ func ==(lhs: ARTAuthOptions, rhs: ARTAuthOptions) -> Bool { class PublishTestMessage { var completion: Optional<(ARTErrorInfo?)->()> - var error: ARTErrorInfo? = ARTErrorInfo.createFromNSError(NSError(domain: "", code: -1, userInfo: nil)) + var error: ARTErrorInfo? = ARTErrorInfo.create(from: NSError(domain: "", code: -1, userInfo: nil)) init(client: ARTRest, failOnError: Bool = true, completion: Optional<(ARTErrorInfo?)->()> = nil) { client.channels.get("test").publish(nil, data: "message") { error in @@ -359,15 +359,15 @@ class PublishTestMessage { client.connection.on { stateChange in let stateChange = stateChange! let state = stateChange.current - if state == .Connected { + if state == .connected { let channel = client.channels.get("test") channel.on { stateChange in switch stateChange!.current { - case .Attached: + case .attached: channel.publish(nil, data: "message") { errorInfo in complete(errorInfo) } - case .Failed: + case .failed: complete(stateChange!.reason) default: break @@ -381,28 +381,28 @@ class PublishTestMessage { } /// Rest - Publish message -func publishTestMessage(rest: ARTRest, completion: Optional<(ARTErrorInfo?)->()>) -> PublishTestMessage { +@discardableResult func publishTestMessage(_ rest: ARTRest, completion: Optional<(ARTErrorInfo?)->()>) -> PublishTestMessage { return PublishTestMessage(client: rest, failOnError: false, completion: completion) } -func publishTestMessage(rest: ARTRest, failOnError: Bool = true) -> PublishTestMessage { +@discardableResult func publishTestMessage(_ rest: ARTRest, failOnError: Bool = true) -> PublishTestMessage { return PublishTestMessage(client: rest, failOnError: failOnError) } /// Realtime - Publish message with callback /// (publishes if connection state changes to CONNECTED and channel state changes to ATTACHED) -func publishFirstTestMessage(realtime: ARTRealtime, completion: Optional<(ARTErrorInfo?)->()>) -> PublishTestMessage { +@discardableResult func publishFirstTestMessage(_ realtime: ARTRealtime, completion: Optional<(ARTErrorInfo?)->()>) -> PublishTestMessage { return PublishTestMessage(client: realtime, failOnError: false, completion: completion) } /// Realtime - Publish message /// (publishes if connection state changes to CONNECTED and channel state changes to ATTACHED) -func publishFirstTestMessage(realtime: ARTRealtime, failOnError: Bool = true) -> PublishTestMessage { +@discardableResult func publishFirstTestMessage(_ realtime: ARTRealtime, failOnError: Bool = true) -> PublishTestMessage { return PublishTestMessage(client: realtime, failOnError: failOnError) } /// Access Token -func getTestToken(key key: String? = nil, clientId: String? = nil, capability: String? = nil, ttl: NSTimeInterval? = nil) -> String { +func getTestToken(key: String? = nil, clientId: String? = nil, capability: String? = nil, ttl: TimeInterval? = nil) -> String { if let tokenDetails = getTestTokenDetails(key: key, clientId: clientId, capability: capability, ttl: ttl) { return tokenDetails.token } @@ -413,7 +413,7 @@ func getTestToken(key key: String? = nil, clientId: String? = nil, capability: S } /// Access TokenDetails -func getTestTokenDetails(key key: String? = nil, clientId: String? = nil, capability: String? = nil, ttl: NSTimeInterval? = nil, completion: (ARTTokenDetails?, NSError?) -> Void) { +func getTestTokenDetails(key: String? = nil, clientId: String? = nil, capability: String? = nil, ttl: TimeInterval? = nil, completion: @escaping (ARTTokenDetails?, Error?) -> Void) { let options: ARTClientOptions if let key = key { options = AblyTests.clientOptions() @@ -439,12 +439,12 @@ func getTestTokenDetails(key key: String? = nil, clientId: String? = nil, capabi tokenParams!.clientId = clientId } - client.auth.requestToken(tokenParams, withOptions: nil, callback: completion) + client.auth.requestToken(tokenParams, with: nil, callback: completion) } -func getTestTokenDetails(key key: String? = nil, clientId: String? = nil, capability: String? = nil, ttl: NSTimeInterval? = nil) -> ARTTokenDetails? { +func getTestTokenDetails(key: String? = nil, clientId: String? = nil, capability: String? = nil, ttl: TimeInterval? = nil) -> ARTTokenDetails? { var tokenDetails: ARTTokenDetails? - var error: NSError? + var error: Error? getTestTokenDetails(key: key, clientId: clientId, capability: capability, ttl: ttl) { _tokenDetails, _error in tokenDetails = _tokenDetails @@ -452,22 +452,18 @@ func getTestTokenDetails(key key: String? = nil, clientId: String? = nil, capabi } while tokenDetails == nil && error == nil { - CFRunLoopRunInMode(kCFRunLoopDefaultMode, CFTimeInterval(0.1), Bool(0)) + CFRunLoopRunInMode(CFRunLoopMode.defaultMode, CFTimeInterval(0.1), Bool(0)) } if let e = error { - XCTFail(e.description) + XCTFail(e.localizedDescription) } return tokenDetails } -public func delay(seconds: NSTimeInterval, closure: ()->()) { - dispatch_after( - dispatch_time( - DISPATCH_TIME_NOW, - Int64(seconds * Double(NSEC_PER_SEC)) - ), - dispatch_get_main_queue(), closure) +public func delay(_ seconds: TimeInterval, closure: @escaping ()->()) { + DispatchQueue.main.asyncAfter( + deadline: DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } class Box { @@ -478,80 +474,80 @@ class Box { } enum Result { - case Success(Box) - case Failure(String) + case success(Box) + case failure(String) /// Constructs a success wrapping a `value`. init(value: Box) { - self = .Success(value) + self = .success(value) } /// Constructs a failure wrapping an `error`. init(error: String) { - self = .Failure(error) + self = .failure(error) } } -func extractURL(request: NSURLRequest?) -> Result { +func extractURL(_ request: URLRequest?) -> Result { guard let request = request else { return Result(error: "No request found") } - guard let url = request.URL + guard let url = request.url else { return Result(error: "Request has no URL defined") } - return Result.Success(Box(url)) + return Result.success(Box(url)) } -func extractBodyAsJSON(request: NSURLRequest?) -> Result { +func extractBodyAsJSON(_ request: URLRequest?) -> Result { guard let request = request else { return Result(error: "No request found") } - guard let bodyData = request.HTTPBody + guard let bodyData = request.httpBody else { return Result(error: "No HTTPBody") } - guard let json = try? NSJSONSerialization.JSONObjectWithData(bodyData, options: .MutableLeaves) + guard let json = try? JSONSerialization.jsonObject(with: bodyData, options: .mutableLeaves) else { return Result(error: "Invalid json") } guard let httpBody = json as? NSDictionary else { return Result(error: "HTTPBody has invalid format") } - return Result.Success(Box(httpBody)) + return Result.success(Box(httpBody)) } -func extractBodyAsMsgPack(request: NSURLRequest?) -> Result { +func extractBodyAsMsgPack(_ request: URLRequest?) -> Result { guard let request = request else { return Result(error: "No request found") } - guard let bodyData = request.HTTPBody + guard let bodyData = request.httpBody else { return Result(error: "No HTTPBody") } let json = try! ARTMsgPackEncoder().decode(bodyData) guard let httpBody = json as? NSDictionary - else { return Result(error: "expected dictionary, got \(json.dynamicType): \(json)") } + else { return Result(error: "expected dictionary, got \(type(of: (json) as AnyObject)): \(json)") } - return Result.Success(Box(httpBody)) + return Result.success(Box(httpBody)) } -func extractBodyAsMessages(request: NSURLRequest?) -> Result<[NSDictionary]> { +func extractBodyAsMessages(_ request: URLRequest?) -> Result<[NSDictionary]> { guard let request = request else { return Result(error: "No request found") } - guard let bodyData = request.HTTPBody + guard let bodyData = request.httpBody else { return Result(error: "No HTTPBody") } let json = try! ARTMsgPackEncoder().decode(bodyData) guard let httpBody = json as? NSArray - else { return Result(error: "expected array, got \(json.dynamicType): \(json)") } + else { return Result(error: "expected array, got \(type(of: (json) as AnyObject)): \(json)") } - return Result.Success(Box(httpBody.map{$0 as! NSDictionary})) + return Result.success(Box(httpBody.map{$0 as! NSDictionary})) } enum NetworkAnswer { - case NoInternet - case HostUnreachable - case RequestTimeout(timeout: NSTimeInterval) - case HostInternalError(code: Int) - case Host400BadRequest + case noInternet + case hostUnreachable + case requestTimeout(timeout: TimeInterval) + case hostInternalError(code: Int) + case host400BadRequest } class MockHTTP: ARTHttp { @@ -562,21 +558,21 @@ class MockHTTP: ARTHttp { self.network = network } - override func executeRequest(request: NSURLRequest, completion callback: ((NSHTTPURLResponse?, NSData?, NSError?) -> Void)?) { + override public func execute(_ request: URLRequest, completion callback: ((HTTPURLResponse?, Data?, Error?) -> Void)? = nil) { delay(0.0) { // Delay to simulate asynchronicity. switch self.network { - case .NoInternet: + case .noInternet: callback?(nil, nil, NSError(domain: NSURLErrorDomain, code: -1009, userInfo: [NSLocalizedDescriptionKey: "The Internet connection appears to be offline.."])) - case .HostUnreachable: + case .hostUnreachable: callback?(nil, nil, NSError(domain: NSURLErrorDomain, code: -1003, userInfo: [NSLocalizedDescriptionKey: "A server with the specified hostname could not be found."])) - case .RequestTimeout(let timeout): + case .requestTimeout(let timeout): delay(timeout) { callback?(nil, nil, NSError(domain: NSURLErrorDomain, code: -1001, userInfo: [NSLocalizedDescriptionKey: "The request timed out."])) } - case .HostInternalError(let code): - callback?(NSHTTPURLResponse(URL: NSURL(string: "http://ios.test.suite")!, statusCode: code, HTTPVersion: nil, headerFields: nil), nil, nil) - case .Host400BadRequest: - callback?(NSHTTPURLResponse(URL: NSURL(string: "http://ios.test.suite")!, statusCode: 400, HTTPVersion: nil, headerFields: nil), nil, nil) + case .hostInternalError(let code): + callback?(HTTPURLResponse(url: URL(string: "http://ios.test.suite")!, statusCode: code, httpVersion: nil, headerFields: nil), nil, nil) + case .host400BadRequest: + callback?(HTTPURLResponse(url: URL(string: "http://ios.test.suite")!, statusCode: 400, httpVersion: nil, headerFields: nil), nil, nil) } } } @@ -585,16 +581,15 @@ class MockHTTP: ARTHttp { /// Records each request and response for test purpose. class TestProxyHTTPExecutor: NSObject, ARTHTTPExecutor { - struct ErrorSimulator { let value: Int let description: String let serverId = "server-test-suite" var statusCode: Int = 401 - mutating func stubResponse(url: NSURL) -> NSHTTPURLResponse? { - return NSHTTPURLResponse(URL: url, statusCode: statusCode, HTTPVersion: "HTTP/1.1", headerFields: [ - "Content-Length": String(stubData?.length ?? 0), + mutating func stubResponse(_ url: URL) -> HTTPURLResponse? { + return HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: [ + "Content-Length": String(stubData?.count ?? 0), "Content-Type": "application/json", "X-Ably-Errorcode": String(value), "X-Ably-Errormessage": description, @@ -603,7 +598,7 @@ class TestProxyHTTPExecutor: NSObject, ARTHTTPExecutor { ) } - lazy var stubData: NSData? = { + lazy var stubData: Data? = { let jsonObject = ["error": [ "statusCode": modf(Float(self.value)/100).0, //whole number part "code": self.value, @@ -611,28 +606,28 @@ class TestProxyHTTPExecutor: NSObject, ARTHTTPExecutor { "serverId": self.serverId, ] ] - return try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.init(rawValue: 0)) + return try? JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions.init(rawValue: 0)) }() } - private var errorSimulator: ErrorSimulator? + fileprivate var errorSimulator: ErrorSimulator? var http: ARTHttp? = ARTHttp() var logger: ARTLog? - var requests: [NSURLRequest] = [] - var responses: [NSHTTPURLResponse] = [] + var requests: [URLRequest] = [] + var responses: [HTTPURLResponse] = [] - var beforeRequest: Optional<(NSURLRequest, ((NSHTTPURLResponse?, NSData?, NSError?) -> Void)?)->()> = nil - var afterRequest: Optional<(NSURLRequest, ((NSHTTPURLResponse?, NSData?, NSError?) -> Void)?)->()> = nil - var beforeProcessingDataResponse: Optional<(NSData?)->(NSData)> = nil + var beforeRequest: Optional<(URLRequest, ((HTTPURLResponse?, Data?, NSError?) -> Void)?)->()> = nil + var afterRequest: Optional<(URLRequest, ((HTTPURLResponse?, Data?, NSError?) -> Void)?)->()> = nil + var beforeProcessingDataResponse: Optional<(Data?)->(Data)> = nil - func executeRequest(request: NSURLRequest, completion callback: ((NSHTTPURLResponse?, NSData?, NSError?) -> Void)?) { + public func execute(_ request: URLRequest, completion callback: ((HTTPURLResponse?, Data?, Error?) -> Void)? = nil) { guard let http = self.http else { return } self.requests.append(request) - if var simulatedError = errorSimulator, requestURL = request.URL { + if var simulatedError = errorSimulator, var requestURL = request.url { defer { errorSimulator = nil } callback?(simulatedError.stubResponse(requestURL), simulatedError.stubData, nil) return @@ -641,15 +636,15 @@ class TestProxyHTTPExecutor: NSObject, ARTHTTPExecutor { if let performEvent = beforeRequest { performEvent(request, callback) } - http.executeRequest(request, completion: { response, data, error in + http.execute(request, completion: { response, data, error in if let httpResponse = response { self.responses.append(httpResponse) } if let performEvent = self.beforeProcessingDataResponse { - callback?(response, performEvent(data), error) + callback?(response, performEvent(data), error as NSError?) } else { - callback?(response, data, error) + callback?(response, data, error as NSError?) } }) if let performEvent = afterRequest { @@ -657,11 +652,11 @@ class TestProxyHTTPExecutor: NSObject, ARTHTTPExecutor { } } - func simulateIncomingServerErrorOnNextRequest(errorValue: Int, description: String) { + func simulateIncomingServerErrorOnNextRequest(_ errorValue: Int, description: String) { errorSimulator = ErrorSimulator(value: errorValue, description: description, statusCode: 401, stubData: nil) } - func simulateIncomingPayloadOnNextRequest(data: NSData) { + func simulateIncomingPayloadOnNextRequest(_ data: Data) { errorSimulator = ErrorSimulator(value: 0, description: "", statusCode: 200, stubData: data) } @@ -670,16 +665,16 @@ class TestProxyHTTPExecutor: NSObject, ARTHTTPExecutor { /// Records each message for test purpose. class TestProxyTransport: ARTWebSocketTransport { - var lastUrl: NSURL? + var lastUrl: URL? - private(set) var protocolMessagesSent = [ARTProtocolMessage]() - private(set) var protocolMessagesReceived = [ARTProtocolMessage]() - private(set) var protocolMessagesSentIgnored = [ARTProtocolMessage]() + fileprivate(set) var protocolMessagesSent = [ARTProtocolMessage]() + fileprivate(set) var protocolMessagesReceived = [ARTProtocolMessage]() + fileprivate(set) var protocolMessagesSentIgnored = [ARTProtocolMessage]() - private(set) var rawDataSent = [NSData]() - private(set) var rawDataReceived = [NSData]() - private var replacingAcksWithNacks: ARTErrorInfo? - private var ignoreWebSocket = false + fileprivate(set) var rawDataSent = [Data]() + fileprivate(set) var rawDataReceived = [Data]() + fileprivate var replacingAcksWithNacks: ARTErrorInfo? + fileprivate var ignoreWebSocket = false var beforeProcessingSentMessage: Optional<(ARTProtocolMessage)->()> = nil var beforeProcessingReceivedMessage: Optional<(ARTProtocolMessage)->()> = nil @@ -689,16 +684,16 @@ class TestProxyTransport: ARTWebSocketTransport { var ignoreSends = false static var network: NetworkAnswer? = nil - static var networkConnectEvent: Optional<(ARTRealtimeTransport, NSURL)->()> = nil + static var networkConnectEvent: Optional<(ARTRealtimeTransport, URL)->()> = nil - override func connectWithKey(key: String) { + override func connect(withKey key: String) { if let network = TestProxyTransport.network { var hook: AspectToken? hook = SRWebSocket.testSuite_replaceClassMethod(#selector(SRWebSocket.open)) { if TestProxyTransport.network == nil { return } - func performConnectError(secondsForDelay: NSTimeInterval, error: ARTRealtimeTransportError) { + func performConnectError(_ secondsForDelay: TimeInterval, error: ARTRealtimeTransportError) { delay(secondsForDelay) { self.delegate?.realtimeTransportFailed(self, withError: error) hook?.remove() @@ -706,18 +701,18 @@ class TestProxyTransport: ARTWebSocketTransport { } let error = NSError.init(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "TestProxyTransport error"]) switch network { - case .NoInternet, .HostUnreachable: - performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, type: .HostUnreachable, url: self.lastUrl!)) - case .RequestTimeout(let timeout): - performConnectError(0.1 + timeout, error: ARTRealtimeTransportError.init(error: error, type: .Timeout, url: self.lastUrl!)) - case .HostInternalError(let code): + case .noInternet, .hostUnreachable: + performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, type: .hostUnreachable, url: self.lastUrl!)) + case .requestTimeout(let timeout): + performConnectError(0.1 + timeout, error: ARTRealtimeTransportError.init(error: error, type: .timeout, url: self.lastUrl!)) + case .hostInternalError(let code): performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, badResponseCode: code, url: self.lastUrl!)) - case .Host400BadRequest: + case .host400BadRequest: performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, badResponseCode: 400, url: self.lastUrl!)) } } } - super.connectWithKey(key) + super.connect(withKey: key) if let performNetworkConnect = TestProxyTransport.networkConnectEvent { func perform() { @@ -731,14 +726,14 @@ class TestProxyTransport: ARTWebSocketTransport { } } - override func connectWithToken(token: String) { + override func connect(withToken token: String) { if let network = TestProxyTransport.network { var hook: AspectToken? hook = SRWebSocket.testSuite_replaceClassMethod(#selector(SRWebSocket.open)) { if TestProxyTransport.network == nil { return } - func performConnectError(secondsForDelay: NSTimeInterval, error: ARTRealtimeTransportError) { + func performConnectError(_ secondsForDelay: TimeInterval, error: ARTRealtimeTransportError) { delay(secondsForDelay) { self.delegate?.realtimeTransportFailed(self, withError: error) hook?.remove() @@ -746,18 +741,18 @@ class TestProxyTransport: ARTWebSocketTransport { } let error = NSError.init(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "TestProxyTransport error"]) switch network { - case .NoInternet, .HostUnreachable: - performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, type: .HostUnreachable, url: self.lastUrl!)) - case .RequestTimeout(let timeout): - performConnectError(0.1 + timeout, error: ARTRealtimeTransportError.init(error: error, type: .Timeout, url: self.lastUrl!)) - case .HostInternalError(let code): + case .noInternet, .hostUnreachable: + performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, type: .hostUnreachable, url: self.lastUrl!)) + case .requestTimeout(let timeout): + performConnectError(0.1 + timeout, error: ARTRealtimeTransportError.init(error: error, type: .timeout, url: self.lastUrl!)) + case .hostInternalError(let code): performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, badResponseCode: code, url: self.lastUrl!)) - case .Host400BadRequest: + case .host400BadRequest: performConnectError(0.1, error: ARTRealtimeTransportError.init(error: error, badResponseCode: 400, url: self.lastUrl!)) } } } - super.connectWithToken(token) + super.connect(withToken: token) if let performNetworkConnect = TestProxyTransport.networkConnectEvent { func perform() { @@ -771,18 +766,18 @@ class TestProxyTransport: ARTWebSocketTransport { } } - override func setupWebSocket(params: [NSURLQueryItem], withOptions options: ARTClientOptions, resumeKey: String?, connectionSerial: NSNumber?) -> NSURL { - let url = super.setupWebSocket(params, withOptions: options, resumeKey: resumeKey, connectionSerial: connectionSerial) + override func setupWebSocket(_ params: [URLQueryItem], with options: ARTClientOptions, resumeKey: String?, connectionSerial: NSNumber?) -> URL { + let url = super.setupWebSocket(params, with: options, resumeKey: resumeKey, connectionSerial: connectionSerial) lastUrl = url return url } - func send(message: ARTProtocolMessage) { - let data = try! encoder.encodeProtocolMessage(message) + func send(_ message: ARTProtocolMessage) { + let data = try! encoder.encode(message) send(data, withSource: message) } - override func send(data: NSData, withSource decodedObject: AnyObject?) { + override func send(_ data: Data, withSource decodedObject: Any?) { if let msg = decodedObject as? ARTProtocolMessage { if ignoreSends { protocolMessagesSentIgnored.append(msg) @@ -797,10 +792,10 @@ class TestProxyTransport: ARTWebSocketTransport { super.send(data, withSource: decodedObject) } - override func receive(msg: ARTProtocolMessage) { - if msg.action == .Ack || msg.action == .Presence { + override func receive(_ msg: ARTProtocolMessage) { + if msg.action == .ack || msg.action == .presence { if let error = replacingAcksWithNacks { - msg.action = .Nack + msg.action = .nack msg.error = error } } @@ -817,20 +812,20 @@ class TestProxyTransport: ARTWebSocketTransport { } } - override func receiveWithData(data: NSData) -> ARTProtocolMessage? { + override func receive(with data: Data) -> ARTProtocolMessage? { rawDataReceived.append(data) - return super.receiveWithData(data) + return super.receive(with: data) } - func replaceAcksWithNacks(error: ARTErrorInfo, block: (doneReplacing: () -> Void) -> Void) { + func replaceAcksWithNacks(_ error: ARTErrorInfo, block: (_ doneReplacing: @escaping () -> Void) -> Void) { replacingAcksWithNacks = error - block(doneReplacing: { self.replacingAcksWithNacks = nil }) + block({ self.replacingAcksWithNacks = nil }) } func simulateTransportSuccess() { self.ignoreWebSocket = true let msg = ARTProtocolMessage() - msg.action = .Connected + msg.action = .connected msg.connectionId = "x-xxxxxxxx" msg.connectionKey = "xxxxxxx-xxxxxxxxxxxxxx-xxxxxxxx" msg.connectionSerial = -1 @@ -838,25 +833,25 @@ class TestProxyTransport: ARTWebSocketTransport { super.receive(msg) } - override func webSocketDidOpen(webSocket: SRWebSocket) { + override func webSocketDidOpen(_ webSocket: SRWebSocket) { if !ignoreWebSocket { super.webSocketDidOpen(webSocket) } } - override func webSocket(webSocket: SRWebSocket, didFailWithError error: NSError) { + override func webSocket(_ webSocket: SRWebSocket, didFailWithError error: Error) { if !ignoreWebSocket { super.webSocket(webSocket, didFailWithError: error) } } - override func webSocket(webSocket: SRWebSocket, didReceiveMessage message: AnyObject?) { + override func webSocket(_ webSocket: SRWebSocket, didReceiveMessage message: Any?) { if !ignoreWebSocket { super.webSocket(webSocket, didReceiveMessage: message) } } - override func webSocket(webSocket: SRWebSocket, didCloseWithCode code: Int, reason: String, wasClean: Bool) { + override func webSocket(_ webSocket: SRWebSocket, didCloseWithCode code: Int, reason: String, wasClean: Bool) { if !ignoreWebSocket { super.webSocket(webSocket, didCloseWithCode: code, reason: reason, wasClean: wasClean) } @@ -866,11 +861,11 @@ class TestProxyTransport: ARTWebSocketTransport { // MARK: - Extensions -extension SequenceType where Generator.Element: NSData { +extension Sequence where Iterator.Element == Data { - var toMsgPackArray: [AnyObject] { + func toMsgPackArray() -> [T] { let msgPackEncoder = ARTMsgPackEncoder() - return map({ try! msgPackEncoder.decode($0) }) + return map({ try! msgPackEncoder.decode($0) as! T }) } } @@ -884,7 +879,7 @@ func + (left: Dictionary, right: Dictionary?) -> Dictionary } } -func += (inout left: Dictionary, right: Dictionary?) { +func += (left: inout Dictionary, right: Dictionary?) { guard let right = right else { return } right.forEach { key, value in left.updateValue(value, forKey: key) @@ -893,7 +888,7 @@ func += (inout left: Dictionary, right: Dictionary?) { extension ARTMessage { - public override func isEqual(object: AnyObject?) -> Bool { + open override func isEqual(_ object: Any?) -> Bool { if let other = object as? ARTMessage { return self.name == other.name && self.encoding == other.encoding && @@ -908,19 +903,19 @@ extension ARTMessage { extension NSObject { var toBase64: String { - return (try? NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions(rawValue: 0)).base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))) ?? "" + return (try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0)).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))) ?? "" } } -extension NSData { +extension Data { - override var toBase64: String { - return self.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) + var toBase64: String { + return self.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) } var toUTF8String: String { - return NSString(data: self, encoding: NSUTF8StringEncoding) as! String + return NSString(data: self, encoding: String.Encoding.utf8.rawValue)! as String } } @@ -937,68 +932,37 @@ extension JSON { } - -extension NSDate: Comparable { } - -public func ==(lhs: NSDate, rhs: NSDate) -> Bool { - return (lhs.compare(rhs) == .OrderedSame) -} - -public func <(lhs: NSDate, rhs: NSDate) -> Bool { - return (lhs.compare(rhs) == .OrderedAscending) -} - -public func >(lhs: NSDate, rhs: NSDate) -> Bool { - return (lhs.compare(rhs) == .OrderedDescending) -} - -public func <=(lhs: NSDate, rhs: NSDate) -> Bool { - return (lhs < rhs || lhs == rhs) -} - -public func >=(lhs: NSDate, rhs: NSDate) -> Bool { - return (lhs > rhs || lhs == rhs) -} - -public func -(lhs: NSDate, rhs: NSTimeInterval) -> NSDate { - return lhs.dateByAddingTimeInterval(-rhs) -} - -public func +(lhs: NSDate, rhs: NSTimeInterval) -> NSDate { - return lhs.dateByAddingTimeInterval(rhs) -} - extension NSRegularExpression { - class func match(value: String?, pattern: String) -> Bool { + class func match(_ value: String?, pattern: String) -> Bool { guard let value = value else { return false } - let options = NSRegularExpressionOptions() + let options = NSRegularExpression.Options() let regex = try! NSRegularExpression(pattern: pattern, options: options) - let range = NSMakeRange(0, value.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) - return regex.rangeOfFirstMatchInString(value, options: [], range: range).location != NSNotFound + let range = NSMakeRange(0, value.lengthOfBytes(using: String.Encoding.utf8)) + return regex.rangeOfFirstMatch(in: value, options: [], range: range).location != NSNotFound } - class func extract(value: String?, pattern: String) -> String? { + class func extract(_ value: String?, pattern: String) -> String? { guard let value = value else { return nil } - let options = NSRegularExpressionOptions() + let options = NSRegularExpression.Options() let regex = try! NSRegularExpression(pattern: pattern, options: options) - let range = NSMakeRange(0, value.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) - let result = regex.firstMatchInString(value, options: [], range: range) - guard let textRange = result?.rangeAtIndex(0) else { return nil } - let convertedRange = value.startIndex.advancedBy(textRange.location).. String { - return self.stringByReplacingOccurrencesOfString(value, withString: string, options: NSStringCompareOptions.LiteralSearch, range: nil) + func replace(_ value: String, withString string: String) -> String { + return self.replacingOccurrences(of: value, with: string, options: NSString.CompareOptions.literal, range: nil) } } @@ -1014,10 +978,10 @@ extension ARTRealtime { self.onDisconnected() } - func simulateSuspended(beforeSuspension beforeSuspensionCallback: (done: () -> ()) -> Void) { + func simulateSuspended(beforeSuspension beforeSuspensionCallback: @escaping (_ done: @escaping () -> ()) -> Void) { waitUntil(timeout: testTimeout) { done in - self.connection.once(.Disconnected) { _ in - beforeSuspensionCallback(done: done) + self.connection.once(.disconnected) { _ in + beforeSuspensionCallback(done) self.onSuspended() } self.onDisconnected() @@ -1025,7 +989,7 @@ extension ARTRealtime { } func dispose() { - let names = self.channels.map({ $0.name }) + let names = self.channels.map({ ($0 as! ARTRealtimeChannel).name }) for name in names { self.channels.release(name) } @@ -1038,7 +1002,7 @@ extension ARTWebSocketTransport { func simulateIncomingNormalClose() { let CLOSE_NORMAL = 1000 - self.setState(ARTRealtimeTransportState.Closing) + self.setState(ARTRealtimeTransportState.closing) let webSocketDelegate = self as SRWebSocketDelegate webSocketDelegate.webSocket!(nil, didCloseWithCode: CLOSE_NORMAL, reason: "", wasClean: true) } @@ -1058,15 +1022,15 @@ extension ARTWebSocketTransport { extension ARTAuth { - func testSuite_forceTokenToExpire(file: StaticString = #file, line: UInt = #line) { + func testSuite_forceTokenToExpire(_ file: StaticString = #file, line: UInt = #line) { guard let tokenDetails = self.tokenDetails else { XCTFail("TokenDetails is nil", file: file, line: line) return } self.setTokenDetails(ARTTokenDetails( token: tokenDetails.token, - expires: NSDate().dateByAddingTimeInterval(-1.0), - issued: NSDate().dateByAddingTimeInterval(-1.0), + expires: Date().addingTimeInterval(-1.0), + issued: Date().addingTimeInterval(-1.0), capability: tokenDetails.capability, clientId: tokenDetails.clientId ) @@ -1077,7 +1041,7 @@ extension ARTAuth { extension ARTPresenceMessage { - convenience init(clientId: String, action: ARTPresenceAction, connectionId: String, id: String, timestamp: NSDate = NSDate()) { + convenience init(clientId: String, action: ARTPresenceAction, connectionId: String, id: String, timestamp: Date = Date()) { self.init() self.action = action self.clientId = clientId @@ -1127,24 +1091,23 @@ extension ARTPresenceAction : CustomStringConvertible { // MARK: - Custom Nimble Matchers /// A Nimble matcher that succeeds when two dates are quite the same. -public func beCloseTo(expectedValue: NSDate?) -> MatcherFunc { - return MatcherFunc { actualExpression, failureMessage in +public func beCloseTo(_ expectedValue: Date) -> Predicate { + return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(expectedValue)>" - guard let actualValue = try actualExpression.evaluate() as? NSDate else { return false } - guard let expectedValue = expectedValue else { return false } + guard let actualValue = try actualExpression.evaluate() else { return false } return abs(actualValue.timeIntervalSince1970 - expectedValue.timeIntervalSince1970) < 0.5 } } /// A Nimble matcher that succeeds when a param exists. -public func haveParam(key: String, withValue expectedValue: String) -> NonNilMatcherFunc { - return NonNilMatcherFunc { actualExpression, failureMessage in +public func haveParam(_ key: String, withValue expectedValue: String) -> Predicate { + return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "param <\(key)=\(expectedValue)> exists" guard let actualValue = try actualExpression.evaluate() else { return false } - let queryItems = actualValue.componentsSeparatedByString("&") + let queryItems = actualValue.components(separatedBy: "&") for item in queryItems { - let param = item.componentsSeparatedByString("=") - if let currentKey = param.first, let currentValue = param.last where currentKey == key && currentValue == expectedValue { + let param = item.components(separatedBy: "=") + if let currentKey = param.first, let currentValue = param.last, currentKey == key && currentValue == expectedValue { return true } } @@ -1153,7 +1116,7 @@ public func haveParam(key: String, withValue expectedValue: String) -> NonNilMat } /// A Nimble matcher that succeeds when all Keys from a Dictionary are valid. -public func allKeysPass (passFunc: (U.Key) -> Bool) -> NonNilMatcherFunc { +public func allKeysPass (_ passFunc: @escaping (U.Key) -> Bool) -> Predicate where U: ExpressibleByDictionaryLiteral, U.Iterator.Element == (U.Key, U.Value) { let elementEvaluator: (Expression, FailureMessage) throws -> Bool = { expression, failureMessage in @@ -1162,7 +1125,7 @@ public func allKeysPass (passFunc: (U.Value) -> Bool) -> NonNilMatcherFunc { +public func allValuesPass (_ passFunc: @escaping (U.Value) -> Bool) -> Predicate where U: ExpressibleByDictionaryLiteral, U.Iterator.Element == (U.Key, U.Value) { let elementEvaluator: (Expression, FailureMessage) throws -> Bool = { expression, failureMessage in @@ -1195,7 +1158,7 @@ public func allValuesPass NSData? { + func dataFromHexadecimalString() -> Data? { let data = NSMutableData(capacity: characters.count / 2) - let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .CaseInsensitive) - regex.enumerateMatchesInString(self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in - let byteString = (self as NSString).substringWithRange(match!.range) + let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) + regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in + let byteString = (self as NSString).substring(with: match!.range) var num = UInt8(byteString, radix: 16) - data?.appendBytes(&num, length: 1) + data?.append(&num, length: 1) } - return data + return data as Data? } } @@ -1247,7 +1210,7 @@ extension String { required init(logger: ARTLog) {} - func listenForHost(host: String, callback: (Bool) -> Void) { + func listen(forHost host: String, callback: @escaping (Bool) -> Void) { self.host = host self.callback = callback } @@ -1257,7 +1220,7 @@ extension String { self.callback = nil } - func simulate(reachable reachable: Bool) { + func simulate(_ reachable: Bool) { self.callback!(reachable) } } diff --git a/Spec/Utilities.swift b/Spec/Utilities.swift index 55439cc53..881c0db3f 100644 --- a/Spec/Utilities.swift +++ b/Spec/Utilities.swift @@ -30,7 +30,7 @@ class Utilities: QuickSpec { "statusCode": "401", ] ] - let data = try! NSJSONSerialization.dataWithJSONObject(jsonObject, options: []) + let data = try! JSONSerialization.data(withJSONObject: jsonObject, options: []) guard let protocolMessage = try? jsonEncoder.decodeProtocolMessage(data) else { fail("Decoder has failed"); return } @@ -42,14 +42,14 @@ class Utilities: QuickSpec { it("should encode a protocol message that has invalid data") { let pm = ARTProtocolMessage() - pm.action = .Message + pm.action = .message pm.channel = "foo" pm.messages = [ARTMessage(name: "status", data: NSDate(), clientId: "user")] - var result: NSData? - expect{ result = try jsonEncoder.encodeProtocolMessage(pm) }.to(throwError { error in + var result: Data? + expect{ result = try jsonEncoder.encode(pm) }.to(throwError { error in let e = error as NSError expect(e.domain).to(equal(ARTAblyErrorDomain)) - expect(e.code).to(equal(Int(ARTClientCodeError.InvalidType.rawValue))) + expect((e as! ARTErrorInfo).code).to(equal(Int(ARTClientCodeError.invalidType.rawValue))) expect(e.localizedDescription).to(contain("Invalid type in JSON write")) }) expect(result).to(beNil()) @@ -57,9 +57,9 @@ class Utilities: QuickSpec { it("should decode data with malformed JSON") { let malformedJSON = "{...}" - let data = malformedJSON.dataUsingEncoding(NSUTF8StringEncoding)! + let data = malformedJSON.data(using: String.Encoding.utf8)! var result: AnyObject? - expect{ result = try ARTJsonEncoder().decode(data) }.to(throwError { error in + expect{ result = try ARTJsonEncoder().decode(data) as AnyObject? }.to(throwError { error in let e = error as NSError expect(e.localizedDescription).to(contain("data couldn’t be read")) }) @@ -69,7 +69,7 @@ class Utilities: QuickSpec { it("should decode data with malformed MsgPack") { let data = NSData() var result: AnyObject? - expect{ result = try ARTMsgPackEncoder().decode(data) }.to(throwError { error in + expect{ result = try ARTMsgPackEncoder().decode(data as Data) as! (Data) as (Data) as AnyObject? }.to(throwError { error in expect(error).toNot(beNil()) }) expect(result).to(beNil()) @@ -110,9 +110,9 @@ class Utilities: QuickSpec { let channel = realtime.channels.get("foo") // Garbage values (whatever is on the heap) - let bytes = UnsafeMutablePointer.alloc(1) - defer { bytes.dealloc(1) } - let data = NSData(bytes: bytes, length: sizeof(Int)) + let bytes = UnsafeMutablePointer.allocate(capacity: 1) + defer { bytes.deallocate(capacity: 1) } + let data = NSData(bytes: bytes, length: MemoryLayout.size) waitUntil(timeout: testTimeout) { done in channel.attach { error in @@ -127,7 +127,7 @@ class Utilities: QuickSpec { fail("Should not receive any message") } var result: AnyObject? - expect{ result = realtime.transport?.receiveWithData(data) }.toNot(raiseException()) + expect{ result = realtime.transport?.receive(with: data as Data) }.toNot(raiseException()) expect(result).to(beNil()) done() } @@ -174,11 +174,11 @@ class Utilities: QuickSpec { let channel = rest.channels.get("foo") // Garbage values (whatever is on the heap) - let bytes = UnsafeMutablePointer.alloc(1) - defer { bytes.dealloc(1) } - let data = NSData(bytes: bytes, length: sizeof(Int)) + let bytes = UnsafeMutablePointer.allocate(capacity: 1) + defer { bytes.deallocate(capacity: 1) } + let data = NSData(bytes: bytes, length: MemoryLayout.size) - testHTTPExecutor.simulateIncomingPayloadOnNextRequest(data) + testHTTPExecutor.simulateIncomingPayloadOnNextRequest(data as Data) waitUntil(timeout: testTimeout) { done in channel.publish(nil, data: nil) { error in expect(error).to(beNil()) //ignored @@ -186,7 +186,7 @@ class Utilities: QuickSpec { } } - testHTTPExecutor.simulateIncomingPayloadOnNextRequest(data) + testHTTPExecutor.simulateIncomingPayloadOnNextRequest(data as Data) waitUntil(timeout: testTimeout) { done in channel.history { result, error in guard let error = error else { @@ -201,7 +201,9 @@ class Utilities: QuickSpec { } context("EventEmitter") { - var eventEmitter = ARTEventEmitter() + + + var eventEmitter = ARTEventEmitter() var receivedFoo1: Int? var receivedFoo2: Int? var receivedBar: Int? @@ -227,37 +229,37 @@ class Utilities: QuickSpec { } it("should emit events to all relevant listeners") { - eventEmitter.emit("foo", with: 123) + eventEmitter.emit("foo", with: 123 as AnyObject?) expect(receivedFoo1).to(equal(123)) expect(receivedFoo2).to(equal(123)) expect(receivedBar).to(beNil()) expect(receivedAll).to(equal(123)) - eventEmitter.emit("bar", with:456) + eventEmitter.emit("bar", with:456 as AnyObject?) expect(receivedFoo1).to(equal(123)) expect(receivedFoo2).to(equal(123)) expect(receivedBar).to(equal(456)) expect(receivedAll).to(equal(456)) - eventEmitter.emit("qux", with:789) + eventEmitter.emit("qux", with:789 as AnyObject?) expect(receivedAll).toEventually(equal(789), timeout: testTimeout) } it("should only call once listeners once for its event") { - eventEmitter.emit("foo", with: 123) + eventEmitter.emit("foo", with: 123 as AnyObject?) expect(receivedBarOnce).to(beNil()) expect(receivedAllOnce).to(equal(123)) - eventEmitter.emit("bar", with: 456) + eventEmitter.emit("bar", with: 456 as AnyObject?) expect(receivedBarOnce).to(equal(456)) expect(receivedAllOnce).to(equal(123)) - eventEmitter.emit("bar", with: 789) + eventEmitter.emit("bar", with: 789 as AnyObject?) expect(receivedBarOnce).to(equal(456)) expect(receivedAllOnce).to(equal(123)) @@ -266,19 +268,19 @@ class Utilities: QuickSpec { context("calling off with a single listener argument") { it("should stop receiving events when calling off with a single listener argument") { eventEmitter.off(listenerFoo1!) - eventEmitter.emit("foo", with: 123) + eventEmitter.emit("foo", with: 123 as AnyObject?) expect(receivedFoo1).to(beNil()) expect(receivedFoo2).to(equal(123)) expect(receivedAll).to(equal(123)) - eventEmitter.emit("bar", with: 222) + eventEmitter.emit("bar", with: 222 as AnyObject?) expect(receivedFoo2).to(equal(123)) expect(receivedAll).to(equal(222)) eventEmitter.off(listenerAll!) - eventEmitter.emit("bar", with: 333) + eventEmitter.emit("bar", with: 333 as AnyObject?) expect(receivedAll).to(equal(222)) } @@ -299,7 +301,7 @@ class Utilities: QuickSpec { context("calling off with listener and event arguments") { it("should still receive events if off doesn't match the listener's criteria") { eventEmitter.off("foo", listener: listenerAll!) - eventEmitter.emit("foo", with: 111) + eventEmitter.emit("foo", with: 111 as AnyObject?) expect(receivedFoo1).to(equal(111)) expect(receivedAll).to(equal(111)) @@ -307,7 +309,7 @@ class Utilities: QuickSpec { it("should stop receive events if off matches the listener's criteria") { eventEmitter.off("foo", listener: listenerFoo1!) - eventEmitter.emit("foo", with: 111) + eventEmitter.emit("foo", with: 111 as AnyObject?) expect(receivedFoo1).to(beNil()) expect(receivedAll).to(equal(111)) @@ -317,13 +319,13 @@ class Utilities: QuickSpec { context("calling off with no arguments") { it("should remove all listeners") { eventEmitter.off() - eventEmitter.emit("foo", with: 111) + eventEmitter.emit("foo", with: 111 as AnyObject?) expect(receivedFoo1).to(beNil()) expect(receivedFoo2).to(beNil()) expect(receivedAll).to(beNil()) - eventEmitter.emit("bar", with: 111) + eventEmitter.emit("bar", with: 111 as AnyObject?) expect(receivedBar).to(beNil()) expect(receivedBarOnce).to(beNil()) @@ -333,7 +335,7 @@ class Utilities: QuickSpec { it("should allow listening again") { eventEmitter.off() eventEmitter.on("foo", callback: { receivedFoo1 = $0 as? Int }) - eventEmitter.emit("foo", with: 111) + eventEmitter.emit("foo", with: 111 as AnyObject?) expect(receivedFoo1).to(equal(111)) } @@ -360,7 +362,7 @@ class Utilities: QuickSpec { }) waitUntil(timeout: 0.4) { done in delay(0.1) { - eventEmitter.emit("foo", with: 123) + eventEmitter.emit("foo", with: 123 as AnyObject?) delay(0.15) { expect(receivedFoo1).toNot(beNil()) done() @@ -375,12 +377,12 @@ class Utilities: QuickSpec { let beforeEmitting = NSDate() listenerFoo1!.setTimer(0.3, onTimeout: { calledOnTimeout = true - expect(NSDate()).to(beCloseTo(beforeEmitting.dateByAddingTimeInterval(0.3), within: 0.2)) + expect(NSDate()).to(beCloseTo(beforeEmitting.addingTimeInterval(0.3), within: 0.2)) }).startTimer() waitUntil(timeout: 0.5) { done in delay(0.35) { expect(calledOnTimeout).to(beTrue()) - eventEmitter.emit("foo", with: 123) + eventEmitter.emit("foo", with: 123 as AnyObject?) expect(receivedFoo1).to(beNil()) done() } @@ -406,11 +408,10 @@ class Utilities: QuickSpec { expect(realtime.logger.history.count).toNot(beGreaterThan(100)) expect(realtime.logger.history.map{ $0.message }.first).to(contain("channel state transitions to 2 - Attached")) - expect(realtime.logger.history.filter{ $0.message.containsString("realtime state transitions to 2 - Connected") }).to(haveCount(1)) + expect(realtime.logger.history.filter{ $0.message.contains("realtime state transitions to 2 - Connected") }).to(haveCount(1)) } } } } } -