FIRMessagingTest.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 <FirebaseMessaging/FIRMessaging.h>
  22. #import "Example/Messaging/Tests/FIRMessagingTestUtilities.h"
  23. #import "Firebase/Messaging/FIRMessaging_Private.h"
  24. extern NSString *const kFIRMessagingFCMTokenFetchAPNSOption;
  25. /// The NSUserDefaults domain for testing.
  26. static 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. // Expose autoInitEnabled static method for IID.
  32. + (BOOL)isAutoInitEnabledWithUserDefaults:(NSUserDefaults *)userDefaults;
  33. // Direct Channel Methods
  34. - (void)updateAutomaticClientConnection;
  35. - (BOOL)shouldBeConnectedAutomatically;
  36. @end
  37. @interface FIRMessagingTest : XCTestCase
  38. @property(nonatomic, readonly, strong) FIRMessaging *messaging;
  39. @property(nonatomic, readwrite, strong) id mockMessaging;
  40. @property(nonatomic, readwrite, strong) id mockInstanceID;
  41. @property(nonatomic, readwrite, strong) id mockFirebaseApp;
  42. @property(nonatomic, strong) FIRMessagingTestUtilities *testUtil;
  43. @end
  44. @implementation FIRMessagingTest
  45. - (void)setUp {
  46. [super setUp];
  47. // Create the messaging instance with all the necessary dependencies.
  48. NSUserDefaults *defaults =
  49. [[NSUserDefaults alloc] initWithSuiteName:kFIRMessagingDefaultsTestDomain];
  50. _testUtil = [[FIRMessagingTestUtilities alloc] initWithUserDefaults:defaults withRMQManager:NO];
  51. _mockMessaging = _testUtil.mockMessaging;
  52. _messaging = _testUtil.messaging;
  53. _mockFirebaseApp = OCMClassMock([FIRApp class]);
  54. OCMStub([_mockFirebaseApp defaultApp]).andReturn(_mockFirebaseApp);
  55. _mockInstanceID = _testUtil.mockInstanceID;
  56. [[NSUserDefaults standardUserDefaults]
  57. removePersistentDomainForName:[NSBundle mainBundle].bundleIdentifier];
  58. }
  59. - (void)tearDown {
  60. [_testUtil cleanupAfterTest];
  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. - (void)testAutoInitEnabledMatchesStaticMethod {
  105. // Flag is set to YES in user defaults.
  106. NSUserDefaults *defaults = self.messaging.messagingUserDefaults;
  107. [defaults setObject:@YES forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  108. XCTAssertTrue(self.messaging.isAutoInitEnabled);
  109. XCTAssertEqual(self.messaging.isAutoInitEnabled,
  110. [FIRMessaging isAutoInitEnabledWithUserDefaults:defaults]);
  111. }
  112. - (void)testAutoInitDisabledMatchesStaticMethod {
  113. // Flag is set to NO in user defaults.
  114. NSUserDefaults *defaults = self.messaging.messagingUserDefaults;
  115. [defaults setObject:@NO forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  116. XCTAssertFalse(self.messaging.isAutoInitEnabled);
  117. XCTAssertEqual(self.messaging.isAutoInitEnabled,
  118. [FIRMessaging isAutoInitEnabledWithUserDefaults:defaults]);
  119. }
  120. #pragma mark - Direct Channel Establishment Testing
  121. #if TARGET_OS_IOS || TARGET_OS_TV
  122. // Should connect with valid token and application in foreground
  123. - (void)testDoesAutomaticallyConnectIfTokenAvailableAndForegrounded {
  124. // Disable actually attempting a connection
  125. [[[_mockMessaging stub] andDo:^(NSInvocation *invocation) {
  126. // Doing nothing on purpose, when -updateAutomaticClientConnection is called
  127. }] updateAutomaticClientConnection];
  128. // Set direct channel to be established after disabling connection attempt
  129. self.messaging.shouldEstablishDirectChannel = YES;
  130. // Set a "valid" token (i.e. not nil or empty)
  131. self.messaging.defaultFcmToken = @"1234567";
  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. XCTAssertTrue(shouldBeConnected);
  138. }
  139. // Should not connect if application is active, but token is empty
  140. - (void)testDoesNotAutomaticallyConnectIfTokenIsEmpty {
  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. // By default, there should be no fcmToken
  148. // Swizzle application state to return UIApplicationStateActive
  149. UIApplication *app = [UIApplication sharedApplication];
  150. id mockApp = OCMPartialMock(app);
  151. [[[mockApp stub] andReturnValue:@(UIApplicationStateActive)] applicationState];
  152. BOOL shouldBeConnected = [_messaging shouldBeConnectedAutomatically];
  153. XCTAssertFalse(shouldBeConnected);
  154. }
  155. // Should not connect if token valid but application isn't active
  156. - (void)testDoesNotAutomaticallyConnectIfApplicationNotActive {
  157. // Disable actually attempting a connection
  158. [[[_mockMessaging stub] andDo:^(NSInvocation *invocation) {
  159. // Doing nothing on purpose, when -updateAutomaticClientConnection is called
  160. }] updateAutomaticClientConnection];
  161. // Set direct channel to be established after disabling connection attempt
  162. self.messaging.shouldEstablishDirectChannel = YES;
  163. // Set a "valid" token (i.e. not nil or empty)
  164. self.messaging.defaultFcmToken = @"abcd1234";
  165. // Swizzle application state to return UIApplicationStateActive
  166. UIApplication *app = [UIApplication sharedApplication];
  167. id mockApp = OCMPartialMock(app);
  168. [[[mockApp stub] andReturnValue:@(UIApplicationStateBackground)] applicationState];
  169. BOOL shouldBeConnected = [_mockMessaging shouldBeConnectedAutomatically];
  170. XCTAssertFalse(shouldBeConnected);
  171. }
  172. #endif
  173. #pragma mark - FCM Token Fetching and Deleting
  174. - (void)testAPNSTokenIncludedInOptionsIfAvailableDuringTokenFetch {
  175. self.messaging.apnsTokenData =
  176. [@"PRETENDING_TO_BE_A_DEVICE_TOKEN" dataUsingEncoding:NSUTF8StringEncoding];
  177. XCTestExpectation *expectation =
  178. [self expectationWithDescription:@"Included APNS Token data in options dict."];
  179. // Inspect the 'options' dictionary to tell whether our expectation was fulfilled
  180. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation) {
  181. NSDictionary *options;
  182. [invocation getArgument:&options atIndex:4];
  183. if (options[@"apns_token"] != nil) {
  184. [expectation fulfill];
  185. }
  186. }] tokenWithAuthorizedEntity:OCMOCK_ANY scope:OCMOCK_ANY options:OCMOCK_ANY handler:OCMOCK_ANY];
  187. self.messaging.instanceID = self.mockInstanceID;
  188. [self.messaging retrieveFCMTokenForSenderID:@"123456"
  189. completion:^(NSString * _Nullable FCMToken,
  190. NSError * _Nullable error) {}];
  191. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  192. }
  193. - (void)testAPNSTokenNotIncludedIfUnavailableDuringTokenFetch {
  194. XCTestExpectation *expectation =
  195. [self expectationWithDescription:@"Included APNS Token data not included in options dict."];
  196. // Inspect the 'options' dictionary to tell whether our expectation was fulfilled
  197. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation) {
  198. NSDictionary *options;
  199. [invocation getArgument:&options atIndex:4];
  200. if (options[@"apns_token"] == nil) {
  201. [expectation fulfill];
  202. }
  203. }] tokenWithAuthorizedEntity:OCMOCK_ANY scope:OCMOCK_ANY options:OCMOCK_ANY handler:OCMOCK_ANY];
  204. [self.messaging retrieveFCMTokenForSenderID:@"123456"
  205. completion:^(NSString * _Nullable FCMToken,
  206. NSError * _Nullable error) {}];
  207. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  208. }
  209. - (void)testReturnsErrorWhenFetchingTokenWithoutSenderID {
  210. XCTestExpectation *expectation =
  211. [self expectationWithDescription:@"Returned an error fetching token without Sender ID"];
  212. #pragma clang diagnostic push
  213. #pragma clang diagnostic ignored "-Wnonnull"
  214. [self.messaging retrieveFCMTokenForSenderID:nil
  215. completion:
  216. ^(NSString * _Nullable FCMToken, 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)testReturnsErrorWhenFetchingTokenWithEmptySenderID {
  225. XCTestExpectation *expectation =
  226. [self expectationWithDescription:@"Returned an error fetching token with empty Sender ID"];
  227. [self.messaging retrieveFCMTokenForSenderID:@""
  228. completion:
  229. ^(NSString * _Nullable FCMToken, NSError * _Nullable error) {
  230. if (error != nil) {
  231. [expectation fulfill];
  232. }
  233. }];
  234. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  235. }
  236. - (void)testReturnsErrorWhenDeletingTokenWithoutSenderID {
  237. XCTestExpectation *expectation =
  238. [self expectationWithDescription:@"Returned an error deleting token without Sender ID"];
  239. #pragma clang diagnostic push
  240. #pragma clang diagnostic ignored "-Wnonnull"
  241. [self.messaging deleteFCMTokenForSenderID:nil completion:^(NSError * _Nullable error) {
  242. if (error != nil) {
  243. [expectation fulfill];
  244. }
  245. }];
  246. #pragma clang diagnostic pop
  247. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  248. }
  249. - (void)testReturnsErrorWhenDeletingTokenWithEmptySenderID {
  250. XCTestExpectation *expectation =
  251. [self expectationWithDescription:@"Returned an error deleting token with empty Sender ID"];
  252. [self.messaging deleteFCMTokenForSenderID:@"" completion:^(NSError * _Nullable error) {
  253. if (error != nil) {
  254. [expectation fulfill];
  255. }
  256. }];
  257. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  258. }
  259. @end