FIRMessagingTest.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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];
  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. self.messaging.shouldEstablishDirectChannel = YES;
  135. // Set a "valid" token (i.e. not nil or empty)
  136. self.messaging.defaultFcmToken = @"1234567";
  137. // Swizzle application state to return UIApplicationStateActive
  138. UIApplication *app = [UIApplication sharedApplication];
  139. id mockApp = OCMPartialMock(app);
  140. [[[mockApp stub] andReturnValue:@(UIApplicationStateActive)] applicationState];
  141. BOOL shouldBeConnected = [_messaging shouldBeConnectedAutomatically];
  142. XCTAssertTrue(shouldBeConnected);
  143. }
  144. // Should not connect if application is active, but token is empty
  145. - (void)testDoesNotAutomaticallyConnectIfTokenIsEmpty {
  146. // Disable actually attempting a connection
  147. [[[_mockMessaging stub] andDo:^(NSInvocation *invocation){
  148. // Doing nothing on purpose, when -updateAutomaticClientConnection is called
  149. }] updateAutomaticClientConnection];
  150. // Set direct channel to be established after disabling connection attempt
  151. self.messaging.shouldEstablishDirectChannel = YES;
  152. // By default, there should be no fcmToken
  153. // Swizzle application state to return UIApplicationStateActive
  154. UIApplication *app = [UIApplication sharedApplication];
  155. id mockApp = OCMPartialMock(app);
  156. [[[mockApp stub] andReturnValue:@(UIApplicationStateActive)] applicationState];
  157. BOOL shouldBeConnected = [_messaging shouldBeConnectedAutomatically];
  158. XCTAssertFalse(shouldBeConnected);
  159. }
  160. // Should not connect if token valid but application isn't active
  161. - (void)testDoesNotAutomaticallyConnectIfApplicationNotActive {
  162. // Disable actually attempting a connection
  163. [[[_mockMessaging stub] andDo:^(NSInvocation *invocation){
  164. // Doing nothing on purpose, when -updateAutomaticClientConnection is called
  165. }] updateAutomaticClientConnection];
  166. // Set direct channel to be established after disabling connection attempt
  167. self.messaging.shouldEstablishDirectChannel = YES;
  168. // Set a "valid" token (i.e. not nil or empty)
  169. self.messaging.defaultFcmToken = @"abcd1234";
  170. // Swizzle application state to return UIApplicationStateActive
  171. UIApplication *app = [UIApplication sharedApplication];
  172. id mockApp = OCMPartialMock(app);
  173. [[[mockApp stub] andReturnValue:@(UIApplicationStateBackground)] applicationState];
  174. BOOL shouldBeConnected = [_mockMessaging shouldBeConnectedAutomatically];
  175. XCTAssertFalse(shouldBeConnected);
  176. }
  177. #endif
  178. #pragma mark - FCM Token Fetching and Deleting
  179. - (void)testAPNSTokenIncludedInOptionsIfAvailableDuringTokenFetch {
  180. self.messaging.apnsTokenData =
  181. [@"PRETENDING_TO_BE_A_DEVICE_TOKEN" dataUsingEncoding:NSUTF8StringEncoding];
  182. XCTestExpectation *expectation =
  183. [self expectationWithDescription:@"Included APNS Token data in options dict."];
  184. // Inspect the 'options' dictionary to tell whether our expectation was fulfilled
  185. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation) {
  186. NSDictionary *options;
  187. [invocation getArgument:&options atIndex:4];
  188. if (options[@"apns_token"] != nil) {
  189. [expectation fulfill];
  190. }
  191. }] tokenWithAuthorizedEntity:OCMOCK_ANY scope:OCMOCK_ANY options:OCMOCK_ANY handler:OCMOCK_ANY];
  192. self.messaging.instanceID = self.mockInstanceID;
  193. [self.messaging
  194. retrieveFCMTokenForSenderID:@"123456"
  195. completion:^(NSString *_Nullable FCMToken, NSError *_Nullable error){
  196. }];
  197. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  198. }
  199. - (void)testAPNSTokenNotIncludedIfUnavailableDuringTokenFetch {
  200. XCTestExpectation *expectation =
  201. [self expectationWithDescription:@"Included APNS Token data not included in options dict."];
  202. // Inspect the 'options' dictionary to tell whether our expectation was fulfilled
  203. [[[self.mockInstanceID stub] andDo:^(NSInvocation *invocation) {
  204. NSDictionary *options;
  205. [invocation getArgument:&options atIndex:4];
  206. if (options[@"apns_token"] == nil) {
  207. [expectation fulfill];
  208. }
  209. }] tokenWithAuthorizedEntity:OCMOCK_ANY scope:OCMOCK_ANY options:OCMOCK_ANY handler:OCMOCK_ANY];
  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)testReturnsErrorWhenFetchingTokenWithoutSenderID {
  217. XCTestExpectation *expectation =
  218. [self expectationWithDescription:@"Returned an error fetching token without Sender ID"];
  219. #pragma clang diagnostic push
  220. #pragma clang diagnostic ignored "-Wnonnull"
  221. [self.messaging
  222. retrieveFCMTokenForSenderID:nil
  223. completion:^(NSString *_Nullable FCMToken, NSError *_Nullable error) {
  224. if (error != nil) {
  225. [expectation fulfill];
  226. }
  227. }];
  228. #pragma clang diagnostic pop
  229. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  230. }
  231. - (void)testReturnsErrorWhenFetchingTokenWithEmptySenderID {
  232. XCTestExpectation *expectation =
  233. [self expectationWithDescription:@"Returned an error fetching token with empty Sender ID"];
  234. [self.messaging
  235. retrieveFCMTokenForSenderID:@""
  236. completion:^(NSString *_Nullable FCMToken, NSError *_Nullable error) {
  237. if (error != nil) {
  238. [expectation fulfill];
  239. }
  240. }];
  241. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  242. }
  243. - (void)testReturnsErrorWhenDeletingTokenWithoutSenderID {
  244. XCTestExpectation *expectation =
  245. [self expectationWithDescription:@"Returned an error deleting token without Sender ID"];
  246. #pragma clang diagnostic push
  247. #pragma clang diagnostic ignored "-Wnonnull"
  248. [self.messaging deleteFCMTokenForSenderID:nil
  249. completion:^(NSError *_Nullable error) {
  250. if (error != nil) {
  251. [expectation fulfill];
  252. }
  253. }];
  254. #pragma clang diagnostic pop
  255. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  256. }
  257. - (void)testReturnsErrorWhenDeletingTokenWithEmptySenderID {
  258. XCTestExpectation *expectation =
  259. [self expectationWithDescription:@"Returned an error deleting token with empty Sender ID"];
  260. [self.messaging deleteFCMTokenForSenderID:@""
  261. completion:^(NSError *_Nullable error) {
  262. if (error != nil) {
  263. [expectation fulfill];
  264. }
  265. }];
  266. [self waitForExpectationsWithTimeout:0.1 handler:nil];
  267. }
  268. @end