FIRMessagingTest.m 11 KB

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