FIRMessagingTest.m 11 KB

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