FIRMessagingTest.m 14 KB

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