FIRMessagingTest.m 11 KB

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