FIRMessagingTest.m 12 KB

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