FIRMessagingTest.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <XCTest/XCTest.h>
  17. #import <OCMock/OCMock.h>
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <FirebaseInstanceID/FirebaseInstanceID.h>
  20. #import "FIRMessaging.h"
  21. #import "FIRMessaging_Private.h"
  22. extern NSString *const kFIRMessagingFCMTokenFetchAPNSOption;
  23. @interface FIRMessaging ()
  24. @property(nonatomic, readwrite, strong) NSString *defaultFcmToken;
  25. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  26. @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
  27. @property(nonatomic, readwrite, strong) NSUserDefaults *messagingUserDefaults;
  28. - (instancetype)initWithInstanceID:(FIRInstanceID *)instanceID
  29. userDefaults:(NSUserDefaults *)defaults;
  30. // Direct Channel Methods
  31. - (void)updateAutomaticClientConnection;
  32. - (BOOL)shouldBeConnectedAutomatically;
  33. @end
  34. @interface FIRMessagingTest : XCTestCase
  35. @property(nonatomic, readonly, strong) FIRMessaging *messaging;
  36. @property(nonatomic, readwrite, strong) id mockMessaging;
  37. @property(nonatomic, readwrite, strong) id mockInstanceID;
  38. @property(nonatomic, readwrite, strong) id mockFirebaseApp;
  39. @end
  40. @implementation FIRMessagingTest
  41. - (void)setUp {
  42. [super setUp];
  43. _mockFirebaseApp = OCMClassMock([FIRApp class]);
  44. OCMStub([_mockFirebaseApp defaultApp]).andReturn(_mockFirebaseApp);
  45. _messaging = [[FIRMessaging alloc] initWithInstanceID:[FIRInstanceID instanceID]
  46. userDefaults:[NSUserDefaults standardUserDefaults]];
  47. _mockMessaging = OCMPartialMock(self.messaging);
  48. _mockInstanceID = OCMPartialMock(self.messaging.instanceID);
  49. self.messaging.instanceID = _mockInstanceID;
  50. [[NSUserDefaults standardUserDefaults]
  51. removePersistentDomainForName:[NSBundle mainBundle].bundleIdentifier];
  52. }
  53. - (void)tearDown {
  54. [_mockMessaging stopMocking];
  55. [_mockInstanceID stopMocking];
  56. [_mockFirebaseApp stopMocking];
  57. [super tearDown];
  58. }
  59. - (void)testAutoInitEnableFlag {
  60. // Should read from Info.plist
  61. XCTAssertFalse(_messaging.isAutoInitEnabled);
  62. // Now set the flag should overwrite Info.plist value.
  63. _messaging.autoInitEnabled = YES;
  64. XCTAssertTrue(_messaging.isAutoInitEnabled);
  65. }
  66. - (void)testAutoInitEnableFlagOverrideGlobalTrue {
  67. OCMStub([_mockFirebaseApp isDataCollectionDefaultEnabled]).andReturn(YES);
  68. id bundleMock = OCMPartialMock([NSBundle mainBundle]);
  69. OCMStub([bundleMock objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled]).andReturn(nil);
  70. XCTAssertTrue(self.messaging.isAutoInitEnabled);
  71. self.messaging.autoInitEnabled = NO;
  72. XCTAssertFalse(self.messaging.isAutoInitEnabled);
  73. [bundleMock stopMocking];
  74. }
  75. - (void)testAutoInitEnableFlagOverrideGlobalFalse {
  76. OCMStub([_mockFirebaseApp isDataCollectionDefaultEnabled]).andReturn(YES);
  77. id bundleMock = OCMPartialMock([NSBundle mainBundle]);
  78. OCMStub([bundleMock objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled]).andReturn(nil);
  79. XCTAssertTrue(self.messaging.isAutoInitEnabled);
  80. self.messaging.autoInitEnabled = NO;
  81. XCTAssertFalse(self.messaging.isAutoInitEnabled);
  82. [bundleMock stopMocking];
  83. }
  84. - (void)testAutoInitEnableGlobalDefaultTrue {
  85. OCMStub([_mockFirebaseApp isDataCollectionDefaultEnabled]).andReturn(YES);
  86. id bundleMock = OCMPartialMock([NSBundle mainBundle]);
  87. OCMStub([bundleMock objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled]).andReturn(nil);
  88. XCTAssertTrue(self.messaging.isAutoInitEnabled);
  89. [bundleMock stopMocking];
  90. }
  91. - (void)testAutoInitEnableGlobalDefaultFalse {
  92. OCMStub([_mockFirebaseApp isDataCollectionDefaultEnabled]).andReturn(NO);
  93. id bundleMock = OCMPartialMock([NSBundle mainBundle]);
  94. OCMStub([bundleMock objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled]).andReturn(nil);
  95. XCTAssertFalse(self.messaging.isAutoInitEnabled);
  96. [bundleMock stopMocking];
  97. }
  98. #pragma mark - Direct Channel Establishment Testing
  99. // Should connect with valid token and application in foreground
  100. - (void)testDoesAutomaticallyConnectIfTokenAvailableAndForegrounded {
  101. // Disable actually attempting a connection
  102. [[[_mockMessaging stub] andDo:^(NSInvocation *invocation) {
  103. // Doing nothing on purpose, when -updateAutomaticClientConnection is called
  104. }] updateAutomaticClientConnection];
  105. // Set direct channel to be established after disabling connection attempt
  106. self.messaging.shouldEstablishDirectChannel = YES;
  107. // Set a "valid" token (i.e. not nil or empty)
  108. self.messaging.defaultFcmToken = @"1234567";
  109. // Swizzle application state to return UIApplicationStateActive
  110. UIApplication *app = [UIApplication sharedApplication];
  111. id mockApp = OCMPartialMock(app);
  112. [[[mockApp stub] andReturnValue:@(UIApplicationStateActive)] applicationState];
  113. BOOL shouldBeConnected = [_mockMessaging shouldBeConnectedAutomatically];
  114. XCTAssertTrue(shouldBeConnected);
  115. }
  116. // Should not connect if application is active, but token is empty
  117. - (void)testDoesNotAutomaticallyConnectIfTokenIsEmpty {
  118. // Disable actually attempting a connection
  119. [[[_mockMessaging stub] andDo:^(NSInvocation *invocation) {
  120. // Doing nothing on purpose, when -updateAutomaticClientConnection is called
  121. }] updateAutomaticClientConnection];
  122. // Set direct channel to be established after disabling connection attempt
  123. self.messaging.shouldEstablishDirectChannel = YES;
  124. // By default, there should be no fcmToken
  125. // Swizzle application state to return UIApplicationStateActive
  126. UIApplication *app = [UIApplication sharedApplication];
  127. id mockApp = OCMPartialMock(app);
  128. [[[mockApp stub] andReturnValue:@(UIApplicationStateActive)] applicationState];
  129. BOOL shouldBeConnected = [_mockMessaging shouldBeConnectedAutomatically];
  130. XCTAssertFalse(shouldBeConnected);
  131. }
  132. // Should not connect if token valid but application isn't active
  133. - (void)testDoesNotAutomaticallyConnectIfApplicationNotActive {
  134. // Disable actually attempting a connection
  135. [[[_mockMessaging stub] andDo:^(NSInvocation *invocation) {
  136. // Doing nothing on purpose, when -updateAutomaticClientConnection is called
  137. }] updateAutomaticClientConnection];
  138. // Set direct channel to be established after disabling connection attempt
  139. self.messaging.shouldEstablishDirectChannel = YES;
  140. // Set a "valid" token (i.e. not nil or empty)
  141. self.messaging.defaultFcmToken = @"abcd1234";
  142. // Swizzle application state to return UIApplicationStateActive
  143. UIApplication *app = [UIApplication sharedApplication];
  144. id mockApp = OCMPartialMock(app);
  145. [[[mockApp stub] andReturnValue:@(UIApplicationStateBackground)] applicationState];
  146. BOOL shouldBeConnected = [_mockMessaging shouldBeConnectedAutomatically];
  147. XCTAssertFalse(shouldBeConnected);
  148. }
  149. #pragma mark - FCM Token Fetching and Deleting
  150. - (void)testAPNSTokenIncludedInOptionsIfAvailableDuringTokenFetch {
  151. self.messaging.apnsTokenData =
  152. [@"PRETENDING_TO_BE_A_DEVICE_TOKEN" dataUsingEncoding:NSUTF8StringEncoding];
  153. XCTestExpectation *expectation =
  154. [self expectationWithDescription:@"Included APNS Token data in options dict."];
  155. // Inspect the 'options' dictionary to tell whether our expectation was fulfilled
  156. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation) {
  157. NSDictionary *options;
  158. [invocation getArgument:&options atIndex:4];
  159. if (options[@"apns_token"] != nil) {
  160. [expectation fulfill];
  161. }
  162. }] tokenWithAuthorizedEntity:OCMOCK_ANY scope:OCMOCK_ANY options:OCMOCK_ANY handler:OCMOCK_ANY];
  163. [self.messaging retrieveFCMTokenForSenderID:@"123456"
  164. completion:^(NSString * _Nullable FCMToken,
  165. NSError * _Nullable error) {}];
  166. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  167. }
  168. - (void)testAPNSTokenNotIncludedIfUnavailableDuringTokenFetch {
  169. XCTestExpectation *expectation =
  170. [self expectationWithDescription:@"Included APNS Token data not included in options dict."];
  171. // Inspect the 'options' dictionary to tell whether our expectation was fulfilled
  172. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation) {
  173. NSDictionary *options;
  174. [invocation getArgument:&options atIndex:4];
  175. if (options[@"apns_token"] == nil) {
  176. [expectation fulfill];
  177. }
  178. }] tokenWithAuthorizedEntity:OCMOCK_ANY scope:OCMOCK_ANY options:OCMOCK_ANY handler:OCMOCK_ANY];
  179. [self.messaging retrieveFCMTokenForSenderID:@"123456"
  180. completion:^(NSString * _Nullable FCMToken,
  181. NSError * _Nullable error) {}];
  182. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  183. }
  184. - (void)testReturnsErrorWhenFetchingTokenWithoutSenderID {
  185. XCTestExpectation *expectation =
  186. [self expectationWithDescription:@"Returned an error fetching token without Sender ID"];
  187. #pragma clang diagnostic push
  188. #pragma clang diagnostic ignored "-Wnonnull"
  189. [self.messaging retrieveFCMTokenForSenderID:nil
  190. completion:
  191. ^(NSString * _Nullable FCMToken, NSError * _Nullable error) {
  192. if (error != nil) {
  193. [expectation fulfill];
  194. }
  195. }];
  196. #pragma clang diagnostic pop
  197. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  198. }
  199. - (void)testReturnsErrorWhenFetchingTokenWithEmptySenderID {
  200. XCTestExpectation *expectation =
  201. [self expectationWithDescription:@"Returned an error fetching token with empty Sender ID"];
  202. [self.messaging retrieveFCMTokenForSenderID:@""
  203. completion:
  204. ^(NSString * _Nullable FCMToken, NSError * _Nullable error) {
  205. if (error != nil) {
  206. [expectation fulfill];
  207. }
  208. }];
  209. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  210. }
  211. - (void)testReturnsErrorWhenDeletingTokenWithoutSenderID {
  212. XCTestExpectation *expectation =
  213. [self expectationWithDescription:@"Returned an error deleting token without Sender ID"];
  214. #pragma clang diagnostic push
  215. #pragma clang diagnostic ignored "-Wnonnull"
  216. [self.messaging deleteFCMTokenForSenderID:nil completion:^(NSError * _Nullable error) {
  217. if (error != nil) {
  218. [expectation fulfill];
  219. }
  220. }];
  221. #pragma clang diagnostic pop
  222. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  223. }
  224. - (void)testReturnsErrorWhenDeletingTokenWithEmptySenderID {
  225. XCTestExpectation *expectation =
  226. [self expectationWithDescription:@"Returned an error deleting token with empty Sender ID"];
  227. [self.messaging deleteFCMTokenForSenderID:@"" completion:^(NSError * _Nullable error) {
  228. if (error != nil) {
  229. [expectation fulfill];
  230. }
  231. }];
  232. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  233. }
  234. @end