FIRMessagingTest.m 11 KB

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