FIRIAMFetchFlowTests.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 "FirebaseInAppMessaging/Sources/Private/Data/FIRIAMMessageContentDataWithImageURL.h"
  19. #import "FirebaseInAppMessaging/Sources/Private/DisplayTrigger/FIRIAMDisplayTriggerDefinition.h"
  20. #import "FirebaseInAppMessaging/Sources/Private/Flows/FIRIAMAnalyticsEventLogger.h"
  21. #import "FirebaseInAppMessaging/Sources/Private/Runtime/FIRIAMFetchFlow.h"
  22. #import "FirebaseInAppMessaging/Sources/Private/Runtime/FIRIAMSDKModeManager.h"
  23. @interface FIRIAMFetchFlow (Testing)
  24. // Expose to verify that this gets called on initial app launch fetch.
  25. - (void)checkForAppLaunchMessage;
  26. @end
  27. @interface FIRIAMFetchFlowTests : XCTestCase
  28. @property(nonatomic) FIRIAMFetchSetting *fetchSetting;
  29. @property FIRIAMMessageClientCache *clientMessageCache;
  30. @property id<FIRIAMMessageFetcher> mockMessageFetcher;
  31. @property id<FIRIAMBookKeeper> mockBookkeeper;
  32. @property id<FIRIAMTimeFetcher> mockTimeFetcher;
  33. @property FIRIAMFetchFlow *flow;
  34. @property FIRIAMActivityLogger *activityLogger;
  35. @property FIRIAMSDKModeManager *mockSDKModeManager;
  36. @property FIRIAMDisplayExecutor *mockDisplayExecutor;
  37. @property id<FIRIAMAnalyticsEventLogger> mockAnaltycisEventLogger;
  38. // three pre-defined messages
  39. @property FIRIAMMessageDefinition *m1, *m2, *m3;
  40. @end
  41. CGFloat FETCH_MIN_INTERVALS = 1;
  42. @implementation FIRIAMFetchFlowTests
  43. - (void)setupMessageTexture {
  44. // startTime, endTime here ensures messages with them are active
  45. NSTimeInterval activeStartTime = 0;
  46. NSTimeInterval activeEndTime = [[NSDate date] timeIntervalSince1970] + 10000;
  47. FIRIAMDisplayTriggerDefinition *triggerDefinition =
  48. [[FIRIAMDisplayTriggerDefinition alloc] initWithFirebaseAnalyticEvent:@"test_event"];
  49. FIRIAMMessageContentDataWithImageURL *m1ContentData =
  50. [[FIRIAMMessageContentDataWithImageURL alloc]
  51. initWithMessageTitle:@"m1 title"
  52. messageBody:@"message body"
  53. actionButtonText:nil
  54. secondaryActionButtonText:nil
  55. actionURL:[NSURL URLWithString:@"http://google.com"]
  56. secondaryActionURL:nil
  57. imageURL:[NSURL URLWithString:@"https://unsplash.it/300/300"]
  58. landscapeImageURL:nil
  59. usingURLSession:nil];
  60. FIRIAMRenderingEffectSetting *renderSetting1 =
  61. [FIRIAMRenderingEffectSetting getDefaultRenderingEffectSetting];
  62. renderSetting1.viewMode = FIRIAMRenderAsBannerView;
  63. FIRIAMMessageRenderData *renderData1 =
  64. [[FIRIAMMessageRenderData alloc] initWithMessageID:@"m1"
  65. messageName:@"name"
  66. contentData:m1ContentData
  67. renderingEffect:renderSetting1];
  68. self.m1 = [[FIRIAMMessageDefinition alloc] initWithRenderData:renderData1
  69. startTime:activeStartTime
  70. endTime:activeEndTime
  71. triggerDefinition:@[ triggerDefinition ]];
  72. FIRIAMMessageContentDataWithImageURL *m2ContentData =
  73. [[FIRIAMMessageContentDataWithImageURL alloc]
  74. initWithMessageTitle:@"m2 title"
  75. messageBody:@"message body"
  76. actionButtonText:nil
  77. secondaryActionButtonText:nil
  78. actionURL:[NSURL URLWithString:@"http://google.com"]
  79. secondaryActionURL:nil
  80. imageURL:[NSURL URLWithString:@"https://unsplash.it/300/400"]
  81. landscapeImageURL:nil
  82. usingURLSession:nil];
  83. FIRIAMRenderingEffectSetting *renderSetting2 =
  84. [FIRIAMRenderingEffectSetting getDefaultRenderingEffectSetting];
  85. renderSetting2.viewMode = FIRIAMRenderAsModalView;
  86. FIRIAMMessageRenderData *renderData2 =
  87. [[FIRIAMMessageRenderData alloc] initWithMessageID:@"m2"
  88. messageName:@"name"
  89. contentData:m2ContentData
  90. renderingEffect:renderSetting2];
  91. self.m2 = [[FIRIAMMessageDefinition alloc] initWithRenderData:renderData2
  92. startTime:activeStartTime
  93. endTime:activeEndTime
  94. triggerDefinition:@[ triggerDefinition ]];
  95. FIRIAMMessageContentDataWithImageURL *m3ContentData =
  96. [[FIRIAMMessageContentDataWithImageURL alloc]
  97. initWithMessageTitle:@"m3 title"
  98. messageBody:@"message body"
  99. actionButtonText:nil
  100. secondaryActionButtonText:nil
  101. actionURL:[NSURL URLWithString:@"http://google.com"]
  102. secondaryActionURL:nil
  103. imageURL:[NSURL URLWithString:@"https://unsplash.it/400/300"]
  104. landscapeImageURL:nil
  105. usingURLSession:nil];
  106. FIRIAMRenderingEffectSetting *renderSetting3 =
  107. [FIRIAMRenderingEffectSetting getDefaultRenderingEffectSetting];
  108. renderSetting3.viewMode = FIRIAMRenderAsImageOnlyView;
  109. FIRIAMMessageRenderData *renderData3 =
  110. [[FIRIAMMessageRenderData alloc] initWithMessageID:@"m3"
  111. messageName:@"name"
  112. contentData:m3ContentData
  113. renderingEffect:renderSetting3];
  114. self.m3 = [[FIRIAMMessageDefinition alloc] initWithRenderData:renderData3
  115. startTime:activeStartTime
  116. endTime:activeEndTime
  117. triggerDefinition:@[ triggerDefinition ]];
  118. }
  119. - (void)setUp {
  120. [super setUp];
  121. [self setupMessageTexture];
  122. self.fetchSetting = [[FIRIAMFetchSetting alloc] init];
  123. self.fetchSetting.fetchMinIntervalInMinutes = FETCH_MIN_INTERVALS;
  124. self.mockMessageFetcher = OCMProtocolMock(@protocol(FIRIAMMessageFetcher));
  125. FIRIAMFetchResponseParser *parser =
  126. [[FIRIAMFetchResponseParser alloc] initWithTimeFetcher:[[FIRIAMTimerWithNSDate alloc] init]];
  127. self.clientMessageCache = [[FIRIAMMessageClientCache alloc] initWithBookkeeper:self.mockBookkeeper
  128. usingResponseParser:parser];
  129. self.mockTimeFetcher = OCMProtocolMock(@protocol(FIRIAMTimeFetcher));
  130. self.mockBookkeeper = OCMProtocolMock(@protocol(FIRIAMBookKeeper));
  131. self.activityLogger = OCMClassMock([FIRIAMActivityLogger class]);
  132. self.mockAnaltycisEventLogger = OCMProtocolMock(@protocol(FIRIAMAnalyticsEventLogger));
  133. self.mockSDKModeManager = OCMClassMock([FIRIAMSDKModeManager class]);
  134. self.mockTimeFetcher = OCMProtocolMock(@protocol(FIRIAMTimeFetcher));
  135. self.mockDisplayExecutor = OCMClassMock([FIRIAMDisplayExecutor class]);
  136. self.flow = [[FIRIAMFetchFlow alloc] initWithSetting:self.fetchSetting
  137. messageCache:self.clientMessageCache
  138. messageFetcher:self.mockMessageFetcher
  139. timeFetcher:self.mockTimeFetcher
  140. bookKeeper:self.mockBookkeeper
  141. activityLogger:self.activityLogger
  142. analyticsEventLogger:self.mockAnaltycisEventLogger
  143. FIRIAMSDKModeManager:self.mockSDKModeManager
  144. displayExecutor:self.mockDisplayExecutor];
  145. }
  146. - (void)tearDown {
  147. // Put teardown code here. This method is called after the invocation of each test method in the
  148. // class.
  149. [super tearDown];
  150. }
  151. // In happy path, the fetch is allowed and we are able to fetch two messages back
  152. - (void)testHappyPath {
  153. OCMStub([self.mockBookkeeper lastFetchTime]).andReturn(0);
  154. // Set it up so that we already have impressions for m1 and m3
  155. FIRIAMImpressionRecord *impression1 =
  156. [[FIRIAMImpressionRecord alloc] initWithMessageID:self.m1.renderData.messageID
  157. impressionTimeInSeconds:1233];
  158. FIRIAMImpressionRecord *impression2 = [[FIRIAMImpressionRecord alloc] initWithMessageID:@"m3"
  159. impressionTimeInSeconds:5678];
  160. NSArray<FIRIAMImpressionRecord *> *impressions = @[ impression1, impression2 ];
  161. OCMStub([self.mockBookkeeper getImpressions]).andReturn(impressions);
  162. NSArray<FIRIAMMessageDefinition *> *fetchedMessages = @[ self.m1, self.m2 ];
  163. // 200 seconds is larger than fetch wait time which is 100 in this setup
  164. OCMStub([self.mockBookkeeper nextFetchWaitTime]).andReturn(100);
  165. OCMStub([self.mockTimeFetcher currentTimestampInSeconds]).andReturn(200);
  166. OCMStub([self.mockSDKModeManager currentMode]).andReturn(FIRIAMSDKModeRegular);
  167. NSNumber *fetchWaitTimeFromResponse = [NSNumber numberWithInt:2000];
  168. OCMStub([self.mockMessageFetcher
  169. fetchMessagesWithImpressionList:[OCMArg any]
  170. withCompletion:([OCMArg invokeBlockWithArgs:fetchedMessages,
  171. fetchWaitTimeFromResponse,
  172. [NSNull null], [NSNull null],
  173. nil])]);
  174. [self.flow checkAndFetchForInitialAppLaunch:NO];
  175. // We expect m1 and m2 to be dumped into clientMessageCache.
  176. NSArray<FIRIAMMessageDefinition *> *foundMessages = [self.clientMessageCache allRegularMessages];
  177. XCTAssertEqual(2, foundMessages.count);
  178. XCTAssertEqualObjects(foundMessages[0].renderData.messageID, self.m1.renderData.messageID);
  179. XCTAssertEqualObjects(foundMessages[1].renderData.messageID, self.m2.renderData.messageID);
  180. // Verify that we record the new fetch with bookkeeper
  181. OCMVerify([self.mockBookkeeper recordNewFetchWithFetchCount:2
  182. withTimestampInSeconds:200
  183. nextFetchWaitTime:fetchWaitTimeFromResponse]);
  184. // So we are sending the request with impression for m1 and m3 and getting back messages for m1
  185. // and m2. In here m1 is a recurring message and after the fetch, we should call
  186. // book keeper's clearImpressionsWithMessageList: method with m1 which is an intersection
  187. // between the request impression list and the response message id list. We are skipping
  188. // m2 since it's not included in the impression records sent along with the request.
  189. OCMVerify(
  190. [self.mockBookkeeper clearImpressionsWithMessageList:@[ self.m1.renderData.messageID ]]);
  191. }
  192. // No fetch is to be performed if the required fetch interval is not met
  193. - (void)testNoFetchDueToIntervalConstraint {
  194. OCMStub([self.mockSDKModeManager currentMode]).andReturn(FIRIAMSDKModeRegular);
  195. // We need to wait at least 300 seconds before making another fetch
  196. OCMStub([self.mockBookkeeper nextFetchWaitTime]).andReturn(300);
  197. // And it's only been 200 seconds since last fetch, so no fetch should happen
  198. OCMStub([self.mockTimeFetcher currentTimestampInSeconds]).andReturn(200);
  199. OCMStub([self.mockBookkeeper lastFetchTime]).andReturn(0);
  200. // We don't expect fetchMessages: for self.mockMessageFetcher to be triggred
  201. OCMReject([self.mockMessageFetcher fetchMessagesWithImpressionList:[OCMArg any]
  202. withCompletion:[OCMArg any]]);
  203. [self.flow checkAndFetchForInitialAppLaunch:NO];
  204. NSArray<FIRIAMMessageDefinition *> *foundMessages = [self.clientMessageCache allRegularMessages];
  205. XCTAssertEqual(0, foundMessages.count);
  206. }
  207. // Fetch always in newly installed mode
  208. - (void)testAlwaysFetchForNewlyInstalledMode {
  209. OCMStub([self.mockBookkeeper lastFetchTime]).andReturn(0);
  210. OCMStub([self.mockSDKModeManager currentMode]).andReturn(FIRIAMSDKModeNewlyInstalled);
  211. OCMStub([self.mockMessageFetcher
  212. fetchMessagesWithImpressionList:[OCMArg any]
  213. withCompletion:([OCMArg invokeBlockWithArgs:@[ self.m1, self.m2 ],
  214. [NSNull null], [NSNull null],
  215. [NSNull null], nil])]);
  216. // 100 seconds is less than fetch wait time which is 1000 in this setup,
  217. // but since we are in newly installed mode, fetch would still happen
  218. OCMStub([self.mockBookkeeper nextFetchWaitTime]).andReturn(1000);
  219. OCMStub([self.mockTimeFetcher currentTimestampInSeconds]).andReturn(100);
  220. [self.flow checkAndFetchForInitialAppLaunch:YES];
  221. // we expect m1 and m2 to be dumped into clientMessageCache
  222. NSArray<FIRIAMMessageDefinition *> *foundMessages = [self.clientMessageCache allRegularMessages];
  223. XCTAssertEqual(2, foundMessages.count);
  224. XCTAssertEqualObjects(foundMessages[0].renderData.messageID, self.m1.renderData.messageID);
  225. XCTAssertEqualObjects(foundMessages[1].renderData.messageID, self.m2.renderData.messageID);
  226. // we expect to register a fetch with sdk manager
  227. OCMVerify([self.mockSDKModeManager registerOneMoreFetch]);
  228. // we expect that the message cache is checked for app launch messages
  229. OCMVerify([self.mockDisplayExecutor checkAndDisplayNextAppLaunchMessage]);
  230. }
  231. // Fetch always in testing app instance mode
  232. - (void)testAlwaysFetchForTestingAppInstanceMode {
  233. OCMStub([self.mockBookkeeper lastFetchTime]).andReturn(0);
  234. OCMStub([self.mockSDKModeManager currentMode]).andReturn(FIRIAMSDKModeTesting);
  235. OCMStub([self.mockMessageFetcher
  236. fetchMessagesWithImpressionList:[OCMArg any]
  237. withCompletion:([OCMArg invokeBlockWithArgs:@[ self.m1, self.m2 ],
  238. [NSNull null], [NSNull null],
  239. [NSNull null], nil])]);
  240. // 100 seconds is less than fetch wait time which is 1000 in this setup,
  241. // but since we are in testing app instance mode, fetch would still happen
  242. OCMStub([self.mockBookkeeper nextFetchWaitTime]).andReturn(1000);
  243. OCMStub([self.mockTimeFetcher currentTimestampInSeconds]).andReturn(100);
  244. [self.flow checkAndFetchForInitialAppLaunch:NO];
  245. // we expect m1 and m2 to be dumped into clientMessageCache
  246. NSArray<FIRIAMMessageDefinition *> *foundMessages = [self.clientMessageCache allRegularMessages];
  247. XCTAssertEqual(2, foundMessages.count);
  248. XCTAssertEqualObjects(foundMessages[0].renderData.messageID, self.m1.renderData.messageID);
  249. XCTAssertEqualObjects(foundMessages[1].renderData.messageID, self.m2.renderData.messageID);
  250. // we expect to register a fetch with sdk manager
  251. OCMVerify([self.mockSDKModeManager registerOneMoreFetch]);
  252. }
  253. - (void)testTurnIntoTestigModeOnSeeingTestMessage {
  254. OCMStub([self.mockBookkeeper lastFetchTime]).andReturn(0);
  255. OCMStub([self.mockSDKModeManager currentMode]).andReturn(FIRIAMSDKModeNewlyInstalled);
  256. FIRIAMMessageDefinition *testMessage =
  257. [[FIRIAMMessageDefinition alloc] initTestMessageWithRenderData:self.m2.renderData
  258. experimentPayload:nil];
  259. OCMStub([self.mockMessageFetcher
  260. fetchMessagesWithImpressionList:[OCMArg any]
  261. withCompletion:([OCMArg invokeBlockWithArgs:@[ self.m1, testMessage ],
  262. [NSNull null], [NSNull null],
  263. [NSNull null], nil])]);
  264. self.fetchSetting.fetchMinIntervalInMinutes = 10; // at least 600 seconds between fetches
  265. // 100 seconds is larger than FETCH_MIN_INTERVALS minutes
  266. OCMStub([self.mockTimeFetcher currentTimestampInSeconds]).andReturn(100);
  267. [self.flow checkAndFetchForInitialAppLaunch:NO];
  268. // Expecting turning sdk mode into a testing instance
  269. OCMVerify([self.mockSDKModeManager becomeTestingInstance]);
  270. }
  271. - (void)testNotTurningIntoTestingModeIfAlreadyInTestingMode {
  272. OCMStub([self.mockBookkeeper lastFetchTime]).andReturn(0);
  273. OCMStub([self.mockSDKModeManager currentMode]).andReturn(FIRIAMSDKModeTesting);
  274. FIRIAMMessageDefinition *testMessage =
  275. [[FIRIAMMessageDefinition alloc] initTestMessageWithRenderData:self.m2.renderData
  276. experimentPayload:nil];
  277. OCMStub([self.mockMessageFetcher
  278. fetchMessagesWithImpressionList:[OCMArg any]
  279. withCompletion:([OCMArg invokeBlockWithArgs:@[ self.m1, testMessage ],
  280. [NSNull null], [NSNull null],
  281. [NSNull null], nil])]);
  282. self.fetchSetting.fetchMinIntervalInMinutes = 10; // at least 600 seconds between fetches
  283. OCMStub([self.mockTimeFetcher currentTimestampInSeconds]).andReturn(1000);
  284. OCMReject([self.mockSDKModeManager becomeTestingInstance]);
  285. [self.flow checkAndFetchForInitialAppLaunch:NO];
  286. }
  287. @end