FIRMessagingTest.m 13 KB

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