RCNRemoteConfigTest.m 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  1. /*
  2. * Copyright 2019 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 <OCMock/OCMStubRecorder.h>
  17. #import <OCMock/OCMock.h>
  18. #import <XCTest/XCTest.h>
  19. #import "FirebaseRemoteConfig/Sources/FIRRemoteConfigComponent.h"
  20. #import "FirebaseRemoteConfig/Sources/Private/FIRRemoteConfig_Private.h"
  21. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigFetch.h"
  22. #import "FirebaseRemoteConfig/Sources/Public/FirebaseRemoteConfig/FIRRemoteConfig.h"
  23. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  24. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  25. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNConfigRealtime.h"
  27. #import "FirebaseRemoteConfig/Sources/RCNUserDefaultsManager.h"
  28. #import "FirebaseRemoteConfig/Tests/Unit/RCNTestUtilities.h"
  29. #import <GoogleUtilities/GULNSData+zlib.h>
  30. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  31. @import FirebaseRemoteConfigInterop;
  32. @protocol FIRRolloutsStateSubscriber;
  33. @interface RCNConfigFetch (ForTest)
  34. - (instancetype)initWithContent:(RCNConfigContent *)content
  35. DBManager:(RCNConfigDBManager *)DBManager
  36. settings:(RCNConfigSettings *)settings
  37. experiment:(RCNConfigExperiment *)experiment
  38. queue:(dispatch_queue_t)queue
  39. namespace:firebaseNamespace
  40. app:firebaseApp;
  41. /// Skip fetching user properties from analytics because we cannot mock the action here. Instead
  42. /// overriding the method to skip.
  43. - (void)fetchWithUserPropertiesCompletionHandler:(NSString *)fetchTypeHeader
  44. completionHandler:(FIRAInteropUserPropertiesCallback)block;
  45. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  46. fetchTypeHeader:(NSString *)fetchTypeHeader
  47. completionHandler:
  48. (RCNConfigFetcherCompletion)fetcherCompletion;
  49. - (void)fetchConfigWithExpirationDuration:(NSTimeInterval)expirationDuration
  50. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler;
  51. - (void)realtimeFetchConfigWithNoExpirationDuration:(NSInteger)fetchAttemptNumber
  52. completionHandler:(RCNConfigFetchCompletion)completionHandler;
  53. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  54. fetchTypeHeader:(NSString *)fetchTypeHeader
  55. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  56. updateCompletionHandler:(RCNConfigFetchCompletion)updateCompletionHandler;
  57. - (NSString *)constructServerURL;
  58. - (NSURLSession *)currentNetworkSession;
  59. @end
  60. @interface RCNConfigRealtime (ForTest)
  61. - (instancetype _Nonnull)init:(RCNConfigFetch *_Nonnull)configFetch
  62. settings:(RCNConfigSettings *_Nonnull)settings
  63. namespace:(NSString *_Nonnull)namespace
  64. options:(FIROptions *_Nonnull)options;
  65. - (void)fetchLatestConfig:(NSInteger)remainingAttempts targetVersion:(NSInteger)targetVersion;
  66. - (void)scheduleFetch:(NSInteger)remainingAttempts targetVersion:(NSInteger)targetVersion;
  67. - (void)autoFetch:(NSInteger)remainingAttempts targetVersion:(NSInteger)targetVersion;
  68. - (void)beginRealtimeStream;
  69. - (void)pauseRealtimeStream;
  70. - (NSData *)createRequestBody;
  71. - (FIRConfigUpdateListenerRegistration *_Nonnull)addConfigUpdateListener:
  72. (RCNConfigUpdateCompletion _Nonnull)listener;
  73. - (void)removeConfigUpdateListener:(RCNConfigUpdateCompletion _Nonnull)listener;
  74. - (void)evaluateStreamResponse:(NSDictionary *)response error:(NSError *)dataError;
  75. @end
  76. @interface FIRRemoteConfig (ForTest)
  77. - (void)updateWithNewInstancesForConfigFetch:(RCNConfigFetch *)configFetch
  78. configContent:(RCNConfigContent *)configContent
  79. configSettings:(RCNConfigSettings *)configSettings
  80. configExperiment:(RCNConfigExperiment *)configExperiment;
  81. - (void)updateWithNewInstancesForConfigRealtime:(RCNConfigRealtime *)configRealtime;
  82. @end
  83. @implementation FIRRemoteConfig (ForTest)
  84. - (void)updateWithNewInstancesForConfigFetch:(RCNConfigFetch *)configFetch
  85. configContent:(RCNConfigContent *)configContent
  86. configSettings:(RCNConfigSettings *)configSettings
  87. configExperiment:(RCNConfigExperiment *)configExperiment {
  88. [self setValue:configFetch forKey:@"_configFetch"];
  89. [self setValue:configContent forKey:@"_configContent"];
  90. [self setValue:configSettings forKey:@"_settings"];
  91. [self setValue:configExperiment forKey:@"_configExperiment"];
  92. }
  93. - (void)updateWithNewInstancesForConfigRealtime:(RCNConfigRealtime *)configRealtime {
  94. [self setValue:configRealtime forKey:@"_configRealtime"];
  95. }
  96. @end
  97. @interface RCNConfigDBManager (Test)
  98. - (void)removeDatabaseOnDatabaseQueueAtPath:(NSString *)path;
  99. @end
  100. @interface RCNUserDefaultsManager (Test)
  101. + (NSUserDefaults *)sharedUserDefaultsForBundleIdentifier:(NSString *)bundleIdentifier;
  102. @end
  103. @interface RCNConfigSettings (Test)
  104. - (NSString *)nextRequestWithUserProperties:(NSDictionary *)userProperties;
  105. @end
  106. typedef NS_ENUM(NSInteger, RCNTestRCInstance) {
  107. RCNTestRCInstanceDefault,
  108. RCNTestRCInstanceSecondNamespace,
  109. RCNTestRCInstanceSecondApp,
  110. RCNTestRCNumTotalInstances
  111. };
  112. @interface RCNRemoteConfigTest : XCTestCase {
  113. NSTimeInterval _expectationTimeout;
  114. NSTimeInterval _checkCompletionTimeout;
  115. NSMutableArray<FIRRemoteConfig *> *_configInstances;
  116. NSMutableArray<NSDictionary<NSString *, NSString *> *> *_entries;
  117. NSArray<NSDictionary *> *_rolloutMetadata;
  118. NSMutableArray<NSDictionary<NSString *, id> *> *_response;
  119. NSMutableArray<NSData *> *_responseData;
  120. NSMutableArray<NSURLResponse *> *_URLResponse;
  121. NSMutableArray<id> *_configFetch;
  122. NSMutableArray<id> *_configRealtime;
  123. RCNConfigDBManager *_DBManager;
  124. NSUserDefaults *_userDefaults;
  125. NSString *_userDefaultsSuiteName;
  126. NSString *_DBPath;
  127. id _DBManagerMock;
  128. id _experimentMock;
  129. id _userDefaultsMock;
  130. NSString *_fullyQualifiedNamespace;
  131. RCNConfigSettings *_settings;
  132. dispatch_queue_t _queue;
  133. NSString *_namespaceGoogleMobilePlatform;
  134. }
  135. @end
  136. @implementation RCNRemoteConfigTest
  137. - (void)setUp {
  138. [super setUp];
  139. FIRSetLoggerLevel(FIRLoggerLevelMax);
  140. _expectationTimeout = 5;
  141. _checkCompletionTimeout = 1.0;
  142. // Always remove the database at the start of testing.
  143. _DBPath = [RCNTestUtilities remoteConfigPathForTestDatabase];
  144. _DBManagerMock = OCMClassMock([RCNConfigDBManager class]);
  145. OCMStub([_DBManagerMock remoteConfigPathForDatabase]).andReturn(_DBPath);
  146. _DBManager = [[RCNConfigDBManager alloc] init];
  147. _userDefaultsSuiteName = [RCNTestUtilities userDefaultsSuiteNameForTestSuite];
  148. _userDefaults = [[NSUserDefaults alloc] initWithSuiteName:_userDefaultsSuiteName];
  149. _userDefaultsMock = OCMClassMock([RCNUserDefaultsManager class]);
  150. OCMStub([_userDefaultsMock sharedUserDefaultsForBundleIdentifier:[OCMArg any]])
  151. .andReturn(_userDefaults);
  152. _experimentMock = OCMClassMock([RCNConfigExperiment class]);
  153. OCMStub([_experimentMock
  154. updateExperimentsWithHandler:([OCMArg invokeBlockWithArgs:[NSNull null], nil])]);
  155. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  156. _configInstances = [[NSMutableArray alloc] initWithCapacity:3];
  157. _entries = [[NSMutableArray alloc] initWithCapacity:3];
  158. _response = [[NSMutableArray alloc] initWithCapacity:3];
  159. _responseData = [[NSMutableArray alloc] initWithCapacity:3];
  160. _URLResponse = [[NSMutableArray alloc] initWithCapacity:3];
  161. _configFetch = [[NSMutableArray alloc] initWithCapacity:3];
  162. _configRealtime = [[NSMutableArray alloc] initWithCapacity:3];
  163. _namespaceGoogleMobilePlatform = FIRRemoteConfigConstants.FIRNamespaceGoogleMobilePlatform;
  164. // Populate the default, second app, second namespace instances.
  165. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  166. // Fake a response for default instance.
  167. NSMutableDictionary<NSString *, NSString *> *valuesDict = [[NSMutableDictionary alloc] init];
  168. for (int count = 1; count <= 100; count++) {
  169. NSString *key = [NSString stringWithFormat:@"key%d-%d", count, i];
  170. NSString *value = [NSString stringWithFormat:@"value%d-%d", count, i];
  171. valuesDict[key] = value;
  172. }
  173. _entries[i] = valuesDict;
  174. NSString *currentAppName = nil;
  175. FIROptions *currentOptions = nil;
  176. NSString *currentNamespace = nil;
  177. switch (i) {
  178. case RCNTestRCInstanceSecondNamespace:
  179. currentAppName = RCNTestsDefaultFIRAppName;
  180. currentOptions = [self firstAppOptions];
  181. currentNamespace = RCNTestsPerfNamespace;
  182. break;
  183. case RCNTestRCInstanceSecondApp:
  184. currentAppName = RCNTestsSecondFIRAppName;
  185. currentOptions = [self secondAppOptions];
  186. currentNamespace = _namespaceGoogleMobilePlatform;
  187. break;
  188. case RCNTestRCInstanceDefault:
  189. default:
  190. currentAppName = RCNTestsDefaultFIRAppName;
  191. currentOptions = [self firstAppOptions];
  192. currentNamespace = RCNTestsFIRNamespace;
  193. break;
  194. }
  195. _fullyQualifiedNamespace =
  196. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  197. FIRRemoteConfig *config =
  198. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  199. FIROptions:currentOptions
  200. namespace:currentNamespace
  201. DBManager:_DBManager
  202. configContent:configContent
  203. analytics:nil]);
  204. _configInstances[i] = config;
  205. _settings = [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  206. namespace:_fullyQualifiedNamespace
  207. firebaseAppName:currentAppName
  208. googleAppID:currentOptions.googleAppID];
  209. _queue = dispatch_queue_create(
  210. [[NSString stringWithFormat:@"testqueue: %d", i] cStringUsingEncoding:NSUTF8StringEncoding],
  211. DISPATCH_QUEUE_SERIAL);
  212. _configFetch[i] =
  213. OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  214. DBManager:_DBManager
  215. settings:_settings
  216. analytics:nil
  217. experiment:_experimentMock
  218. queue:_queue
  219. namespace:_fullyQualifiedNamespace
  220. options:currentOptions]);
  221. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  222. settings:_settings
  223. namespace:_fullyQualifiedNamespace
  224. options:currentOptions]);
  225. _settings.configInstallationsIdentifier = @"iid";
  226. OCMStubRecorder *mock = OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:0
  227. completionHandler:OCMOCK_ANY]);
  228. mock = [mock ignoringNonObjectArgs];
  229. mock.andDo(^(NSInvocation *invocation) {
  230. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  231. NSError *_Nullable error) = nil;
  232. [invocation getArgument:&handler atIndex:3];
  233. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  234. fetchTypeHeader:@"Base/1"
  235. completionHandler:handler
  236. updateCompletionHandler:nil];
  237. });
  238. _rolloutMetadata = @[ @{
  239. RCNFetchResponseKeyRolloutID : @"1",
  240. RCNFetchResponseKeyVariantID : @"0",
  241. RCNFetchResponseKeyAffectedParameterKeys : @[ _entries[i].allKeys[0] ]
  242. } ];
  243. _response[i] = @{
  244. @"state" : @"UPDATE",
  245. @"entries" : _entries[i],
  246. RCNFetchResponseKeyRolloutMetadata : _rolloutMetadata
  247. };
  248. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  249. _URLResponse[i] = [[NSHTTPURLResponse alloc]
  250. initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  251. statusCode:200
  252. HTTPVersion:nil
  253. headerFields:@{@"etag" : [NSString stringWithFormat:@"etag1-%d", i]}];
  254. id completionBlock =
  255. [OCMArg invokeBlockWithArgs:_responseData[i], _URLResponse[i], [NSNull null], nil];
  256. OCMStub([_configFetch[i] URLSessionDataTaskWithContent:[OCMArg any]
  257. fetchTypeHeader:[OCMArg any]
  258. completionHandler:completionBlock])
  259. .andReturn(nil);
  260. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  261. configContent:configContent
  262. configSettings:_settings
  263. configExperiment:_experimentMock];
  264. [_configInstances[i] updateWithNewInstancesForConfigRealtime:_configRealtime[i]];
  265. }
  266. }
  267. - (void)tearDown {
  268. [_DBManager removeDatabaseOnDatabaseQueueAtPath:_DBPath];
  269. [FIRRemoteConfigComponent clearAllComponentInstances];
  270. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:_userDefaultsSuiteName];
  271. [_DBManagerMock stopMocking];
  272. _DBManagerMock = nil;
  273. [_userDefaultsMock stopMocking];
  274. _userDefaultsMock = nil;
  275. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  276. [(id)_configInstances[i] stopMocking];
  277. [(id)_configFetch[i] stopMocking];
  278. }
  279. [_configInstances removeAllObjects];
  280. [_configFetch removeAllObjects];
  281. [_configRealtime removeAllObjects];
  282. _configInstances = nil;
  283. _configFetch = nil;
  284. [super tearDown];
  285. }
  286. - (void)testFetchConfigWithNilCallback {
  287. NSMutableArray<XCTestExpectation *> *expectations =
  288. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  289. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  290. expectations[i] = [self
  291. expectationWithDescription:
  292. [NSString stringWithFormat:@"Set defaults no callback expectation - instance %d", i]];
  293. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  294. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:nil];
  295. dispatch_after(
  296. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  297. dispatch_get_main_queue(), ^{
  298. XCTAssertEqual(self->_configInstances[i].lastFetchStatus,
  299. FIRRemoteConfigFetchStatusSuccess);
  300. [expectations[i] fulfill];
  301. });
  302. }
  303. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  304. }
  305. - (void)testFetchConfigsSuccessfully {
  306. NSMutableArray<XCTestExpectation *> *expectations =
  307. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  308. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  309. expectations[i] =
  310. [self expectationWithDescription:
  311. [NSString stringWithFormat:@"Test fetch configs successfully - instance %d", i]];
  312. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  313. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  314. NSError *error) {
  315. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  316. XCTAssertNil(error);
  317. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  318. XCTAssertTrue(changed);
  319. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  320. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  321. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  322. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  323. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  324. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  325. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  326. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  327. @"Callback of first successful config "
  328. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccessFresh.");
  329. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  330. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  331. @"last fetch time interval should be set.");
  332. [expectations[i] fulfill];
  333. }];
  334. };
  335. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  336. }
  337. [self waitForExpectationsWithTimeout:_expectationTimeout
  338. handler:^(NSError *error) {
  339. XCTAssertNil(error);
  340. }];
  341. }
  342. - (void)testFetchAndActivate {
  343. NSMutableArray<XCTestExpectation *> *expectations =
  344. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  345. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  346. expectations[i] =
  347. [self expectationWithDescription:
  348. [NSString stringWithFormat:@"Test fetch configs successfully - instance %d", i]];
  349. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  350. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion = ^void(
  351. FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  352. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  353. XCTAssertNil(error);
  354. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  355. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  356. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  357. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  358. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  359. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  360. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  361. XCTAssertEqual(
  362. status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote,
  363. @"Callback of first successful config "
  364. @"fetchAndActivate status must equal to FIRRemoteConfigFetchAndStatusSuccessFromRemote.");
  365. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  366. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  367. @"last fetch time interval should be set.");
  368. [expectations[i] fulfill];
  369. };
  370. // Update the minimum fetch interval to 0. This disables the cache and forces a remote fetch
  371. // request.
  372. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  373. settings.minimumFetchInterval = 0;
  374. [_configInstances[i] setConfigSettings:settings];
  375. [_configInstances[i] fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  376. }
  377. [self waitForExpectationsWithTimeout:_expectationTimeout
  378. handler:^(NSError *error) {
  379. XCTAssertNil(error);
  380. }];
  381. }
  382. // TODO: Try splitting into smaller tests.
  383. - (void)testFetchConfigsSuccessfullyWithNewActivateMethodSignature {
  384. NSMutableArray<XCTestExpectation *> *expectations =
  385. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  386. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  387. expectations[i] =
  388. [self expectationWithDescription:
  389. [NSString stringWithFormat:@"Test fetch configs successfully - instance %d", i]];
  390. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  391. FIRRemoteConfigFetchCompletion fetchCompletion = ^(FIRRemoteConfigFetchStatus status,
  392. NSError *error) {
  393. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  394. XCTAssertNil(error);
  395. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  396. XCTAssertTrue(changed);
  397. XCTAssertNil(error);
  398. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  399. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  400. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  401. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  402. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  403. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  404. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  405. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  406. @"Callback of first successful config "
  407. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccessFresh.");
  408. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  409. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  410. @"last fetch time interval should be set.");
  411. // A second activate should have no effect.
  412. [self->_configInstances[i]
  413. activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  414. XCTAssertFalse(changed);
  415. XCTAssertNil(error);
  416. }];
  417. [expectations[i] fulfill];
  418. }];
  419. };
  420. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  421. }
  422. [self waitForExpectationsWithTimeout:_expectationTimeout
  423. handler:^(NSError *error) {
  424. XCTAssertNil(error);
  425. }];
  426. }
  427. - (void)testEnumeratingConfigResults {
  428. NSMutableArray<XCTestExpectation *> *expectations =
  429. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  430. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  431. expectations[i] = [self
  432. expectationWithDescription:
  433. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  434. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  435. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  436. NSError *error) {
  437. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  438. XCTAssertNil(error);
  439. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  440. XCTAssertTrue(changed);
  441. NSString *key5 = [NSString stringWithFormat:@"key5-%d", i];
  442. NSString *key19 = [NSString stringWithFormat:@"key19-%d", i];
  443. NSString *value5 = [NSString stringWithFormat:@"value5-%d", i];
  444. NSString *value19 = [NSString stringWithFormat:@"value19-%d", i];
  445. XCTAssertEqualObjects(self->_configInstances[i][key5].stringValue, value5);
  446. XCTAssertEqualObjects(self->_configInstances[i][key19].stringValue, value19);
  447. // Test enumerating config values.
  448. for (NSString *key in self->_configInstances[i]) {
  449. if ([key isEqualToString:key5]) {
  450. XCTAssertEqualObjects(self->_configInstances[i][key5].stringValue, value5);
  451. }
  452. if ([key isEqualToString:key19]) {
  453. XCTAssertEqualObjects(self->_configInstances[i][key19].stringValue, value19);
  454. }
  455. }
  456. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  457. @"Callback of first successful config "
  458. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccessFresh.");
  459. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  460. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  461. @"last fetch time interval should be set.");
  462. [expectations[i] fulfill];
  463. }];
  464. };
  465. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  466. }
  467. [self waitForExpectationsWithTimeout:_expectationTimeout
  468. handler:^(NSError *error) {
  469. XCTAssertNil(error);
  470. }];
  471. }
  472. - (void)testFetchAndActivate3pNamespaceUpdatesExperiments {
  473. [[_experimentMock expect] updateExperimentsWithResponse:[OCMArg any]];
  474. XCTestExpectation *expectation = [self
  475. expectationWithDescription:[NSString stringWithFormat:@"FetchAndActivate call for 'firebase' "
  476. @"namespace updates experiment data"]];
  477. XCTAssertEqual(_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  478. FIRRemoteConfigFetchStatusNoFetchYet);
  479. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion =
  480. ^void(FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  481. XCTAssertEqual(status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote);
  482. XCTAssertNil(error);
  483. XCTAssertEqual(self->_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  484. FIRRemoteConfigFetchStatusSuccess);
  485. XCTAssertNotNil(self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime);
  486. XCTAssertGreaterThan(
  487. self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime.timeIntervalSince1970, 0,
  488. @"last fetch time interval should be set.");
  489. [expectation fulfill];
  490. };
  491. [_configInstances[RCNTestRCInstanceDefault]
  492. fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  493. [self waitForExpectationsWithTimeout:_expectationTimeout
  494. handler:^(NSError *error) {
  495. XCTAssertNil(error);
  496. }];
  497. }
  498. - (void)testFetchAndActivateOtherNamespaceDoesntUpdateExperiments {
  499. [[_experimentMock reject] updateExperimentsWithResponse:[OCMArg any]];
  500. XCTestExpectation *expectation = [self
  501. expectationWithDescription:
  502. [NSString stringWithFormat:@"FetchAndActivate call for namespace other than 'firebase' "
  503. @"doesn't update experiment data"]];
  504. XCTAssertEqual(_configInstances[RCNTestRCInstanceSecondNamespace].lastFetchStatus,
  505. FIRRemoteConfigFetchStatusNoFetchYet);
  506. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion =
  507. ^void(FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  508. XCTAssertEqual(status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote);
  509. XCTAssertNil(error);
  510. XCTAssertEqual(self->_configInstances[RCNTestRCInstanceSecondNamespace].lastFetchStatus,
  511. FIRRemoteConfigFetchStatusSuccess);
  512. XCTAssertNotNil(self->_configInstances[RCNTestRCInstanceSecondNamespace].lastFetchTime);
  513. XCTAssertGreaterThan(self->_configInstances[RCNTestRCInstanceSecondNamespace]
  514. .lastFetchTime.timeIntervalSince1970,
  515. 0, @"last fetch time interval should be set.");
  516. [expectation fulfill];
  517. };
  518. [_configInstances[RCNTestRCInstanceSecondNamespace]
  519. fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  520. [self waitForExpectationsWithTimeout:_expectationTimeout
  521. handler:^(NSError *error) {
  522. XCTAssertNil(error);
  523. }];
  524. }
  525. - (void)testFetchConfigsFailed {
  526. // Override the setup values to return back an error status.
  527. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  528. // Populate the default, second app, second namespace instances.
  529. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  530. NSString *currentAppName = nil;
  531. FIROptions *currentOptions = nil;
  532. NSString *currentNamespace = nil;
  533. switch (i) {
  534. case RCNTestRCInstanceSecondNamespace:
  535. currentAppName = RCNTestsDefaultFIRAppName;
  536. currentOptions = [self firstAppOptions];
  537. currentNamespace = RCNTestsPerfNamespace;
  538. break;
  539. case RCNTestRCInstanceSecondApp:
  540. currentAppName = RCNTestsSecondFIRAppName;
  541. currentOptions = [self secondAppOptions];
  542. currentNamespace = _namespaceGoogleMobilePlatform;
  543. break;
  544. case RCNTestRCInstanceDefault:
  545. default:
  546. currentAppName = RCNTestsDefaultFIRAppName;
  547. currentOptions = [self firstAppOptions];
  548. currentNamespace = RCNTestsFIRNamespace;
  549. break;
  550. }
  551. RCNUserDefaultsManager *userDefaultsManager =
  552. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  553. bundleID:[NSBundle mainBundle].bundleIdentifier
  554. namespace:_fullyQualifiedNamespace];
  555. userDefaultsManager.lastFetchTime = 0;
  556. FIRRemoteConfig *config =
  557. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  558. FIROptions:currentOptions
  559. namespace:currentNamespace
  560. DBManager:_DBManager
  561. configContent:configContent
  562. analytics:nil]);
  563. _configInstances[i] = config;
  564. _configFetch[i] =
  565. OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  566. DBManager:_DBManager
  567. settings:_settings
  568. analytics:nil
  569. experiment:nil
  570. queue:_queue
  571. namespace:_fullyQualifiedNamespace
  572. options:currentOptions]);
  573. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  574. settings:_settings
  575. namespace:_fullyQualifiedNamespace
  576. options:currentOptions]);
  577. OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  578. .andDo(^(NSInvocation *invocation) {
  579. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  580. NSError *_Nullable error) = nil;
  581. [invocation getArgument:&handler atIndex:3];
  582. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  583. fetchTypeHeader:@"Base/1"
  584. completionHandler:handler
  585. updateCompletionHandler:nil];
  586. });
  587. _response[i] = @{};
  588. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  589. _URLResponse[i] =
  590. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  591. statusCode:500
  592. HTTPVersion:nil
  593. headerFields:@{@"etag" : @"etag1"}];
  594. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  595. configContent:configContent
  596. configSettings:_settings
  597. configExperiment:nil];
  598. }
  599. // Make the fetch calls for all instances.
  600. NSMutableArray<XCTestExpectation *> *expectations =
  601. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  602. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  603. expectations[i] = [self
  604. expectationWithDescription:
  605. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  606. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  607. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  608. NSError *error) {
  609. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusFailure);
  610. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  611. XCTAssertFalse(changed);
  612. XCTAssertNil(error);
  613. FIRRemoteConfigValue *value = self->_configInstances[RCNTestRCInstanceDefault][@"key1"];
  614. XCTAssertEqual((int)value.source, (int)FIRRemoteConfigSourceStatic);
  615. XCTAssertEqualObjects(value.stringValue, @"");
  616. XCTAssertEqual(value.boolValue, NO);
  617. [expectations[i] fulfill];
  618. }];
  619. };
  620. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  621. }
  622. [self waitForExpectationsWithTimeout:_expectationTimeout
  623. handler:^(NSError *error) {
  624. XCTAssertNil(error);
  625. }];
  626. }
  627. // TODO(mandard): Break up test with helper methods.
  628. - (void)testFetchConfigsFailedErrorNoNetwork {
  629. // Override the setup values to return back an error status.
  630. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  631. // Populate the default, second app, second namespace instances.
  632. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  633. NSString *currentAppName = nil;
  634. FIROptions *currentOptions = nil;
  635. NSString *currentNamespace = nil;
  636. switch (i) {
  637. case RCNTestRCInstanceSecondNamespace:
  638. currentAppName = RCNTestsDefaultFIRAppName;
  639. currentOptions = [self firstAppOptions];
  640. currentNamespace = RCNTestsPerfNamespace;
  641. break;
  642. case RCNTestRCInstanceSecondApp:
  643. currentAppName = RCNTestsSecondFIRAppName;
  644. currentOptions = [self secondAppOptions];
  645. currentNamespace = _namespaceGoogleMobilePlatform;
  646. break;
  647. case RCNTestRCInstanceDefault:
  648. default:
  649. currentAppName = RCNTestsDefaultFIRAppName;
  650. currentOptions = [self firstAppOptions];
  651. currentNamespace = RCNTestsFIRNamespace;
  652. break;
  653. }
  654. NSString *fullyQualifiedNamespace =
  655. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  656. RCNUserDefaultsManager *userDefaultsManager =
  657. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  658. bundleID:[NSBundle mainBundle].bundleIdentifier
  659. namespace:fullyQualifiedNamespace];
  660. userDefaultsManager.lastFetchTime = 0;
  661. FIRRemoteConfig *config =
  662. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  663. FIROptions:currentOptions
  664. namespace:currentNamespace
  665. DBManager:_DBManager
  666. configContent:configContent
  667. analytics:nil]);
  668. _configInstances[i] = config;
  669. RCNConfigSettings *settings =
  670. [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  671. namespace:fullyQualifiedNamespace
  672. firebaseAppName:currentAppName
  673. googleAppID:currentOptions.googleAppID];
  674. dispatch_queue_t queue = dispatch_queue_create(
  675. [[NSString stringWithFormat:@"testqueue: %d", i] cStringUsingEncoding:NSUTF8StringEncoding],
  676. DISPATCH_QUEUE_SERIAL);
  677. _configFetch[i] = OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  678. DBManager:_DBManager
  679. settings:settings
  680. analytics:nil
  681. experiment:nil
  682. queue:queue
  683. namespace:fullyQualifiedNamespace
  684. options:currentOptions]);
  685. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  686. settings:settings
  687. namespace:fullyQualifiedNamespace
  688. options:currentOptions]);
  689. OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  690. .andDo(^(NSInvocation *invocation) {
  691. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  692. NSError *_Nullable error) = nil;
  693. [invocation getArgument:&handler atIndex:3];
  694. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  695. fetchTypeHeader:@"Base/1"
  696. completionHandler:handler
  697. updateCompletionHandler:nil];
  698. });
  699. _response[i] = @{};
  700. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  701. // A no network error is accompanied with an HTTP status code of 0.
  702. _URLResponse[i] =
  703. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  704. statusCode:0
  705. HTTPVersion:nil
  706. headerFields:@{@"etag" : @"etag1"}];
  707. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  708. configContent:configContent
  709. configSettings:settings
  710. configExperiment:nil];
  711. }
  712. // Make the fetch calls for all instances.
  713. NSMutableArray<XCTestExpectation *> *expectations =
  714. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  715. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  716. expectations[i] = [self
  717. expectationWithDescription:
  718. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  719. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  720. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  721. NSError *error) {
  722. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusFailure);
  723. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  724. XCTAssertFalse(changed);
  725. XCTAssertNil(error);
  726. // No such key, still return a static value.
  727. FIRRemoteConfigValue *value = self->_configInstances[RCNTestRCInstanceDefault][@"key1"];
  728. XCTAssertEqual((int)value.source, (int)FIRRemoteConfigSourceStatic);
  729. XCTAssertEqualObjects(value.stringValue, @"");
  730. XCTAssertEqual(value.boolValue, NO);
  731. [expectations[i] fulfill];
  732. }];
  733. };
  734. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  735. }
  736. [self waitForExpectationsWithTimeout:_expectationTimeout
  737. handler:^(NSError *error) {
  738. XCTAssertNil(error);
  739. }];
  740. }
  741. - (void)testFetchFailedNoNetworkErrorDoesNotThrottle {
  742. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  743. NSString *currentAppName = RCNTestsDefaultFIRAppName;
  744. FIROptions *currentOptions = [self firstAppOptions];
  745. NSString *currentNamespace = RCNTestsFIRNamespace;
  746. NSString *fullyQualifiedNamespace =
  747. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  748. RCNUserDefaultsManager *userDefaultsManager =
  749. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  750. bundleID:[NSBundle mainBundle].bundleIdentifier
  751. namespace:fullyQualifiedNamespace];
  752. userDefaultsManager.lastFetchTime = 0;
  753. FIRRemoteConfig *config = OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  754. FIROptions:currentOptions
  755. namespace:currentNamespace
  756. DBManager:_DBManager
  757. configContent:configContent
  758. analytics:nil]);
  759. RCNConfigSettings *settings =
  760. [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  761. namespace:fullyQualifiedNamespace
  762. firebaseAppName:currentAppName
  763. googleAppID:currentOptions.googleAppID];
  764. dispatch_queue_t queue = dispatch_queue_create(
  765. [[NSString stringWithFormat:@"testqueue"] cStringUsingEncoding:NSUTF8StringEncoding],
  766. DISPATCH_QUEUE_SERIAL);
  767. RCNConfigFetch *configFetch =
  768. OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  769. DBManager:_DBManager
  770. settings:settings
  771. analytics:nil
  772. experiment:nil
  773. queue:queue
  774. namespace:fullyQualifiedNamespace
  775. options:currentOptions]);
  776. OCMStub([configFetch fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  777. .andDo(^(NSInvocation *invocation) {
  778. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  779. NSError *_Nullable error) = nil;
  780. [invocation getArgument:&handler atIndex:3];
  781. [configFetch fetchWithUserProperties:[[NSDictionary alloc] init]
  782. fetchTypeHeader:@"Base/1"
  783. completionHandler:handler
  784. updateCompletionHandler:nil];
  785. });
  786. _responseData[0] = [NSJSONSerialization dataWithJSONObject:@{} options:0 error:nil];
  787. // A no network error is accompanied with an HTTP status code of 0.
  788. _URLResponse[0] =
  789. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  790. statusCode:0
  791. HTTPVersion:nil
  792. headerFields:@{@"etag" : @"etag1"}];
  793. [config updateWithNewInstancesForConfigFetch:configFetch
  794. configContent:configContent
  795. configSettings:settings
  796. configExperiment:nil];
  797. XCTestExpectation *expectation =
  798. [self expectationWithDescription:@"Network error doesn't increase throttle interval"];
  799. XCTAssertEqual(config.lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  800. FIRRemoteConfigFetchCompletion fetchCompletion =
  801. ^void(FIRRemoteConfigFetchStatus status, NSError *error) {
  802. XCTAssertEqual(config.lastFetchStatus, FIRRemoteConfigFetchStatusFailure);
  803. XCTAssertEqual(settings.exponentialBackoffRetryInterval, 0);
  804. [expectation fulfill];
  805. };
  806. [config fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  807. [self waitForExpectationsWithTimeout:_expectationTimeout
  808. handler:^(NSError *error) {
  809. XCTAssertNil(error);
  810. }];
  811. }
  812. // Activate should return false if a fetch response returns 200 with NO_CHANGE as the response body.
  813. - (void)testActivateOnFetchNoChangeStatus {
  814. // Override the setup values to return back an error status.
  815. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  816. // Populate the default, second app, second namespace instances.
  817. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  818. NSString *currentAppName = nil;
  819. FIROptions *currentOptions = nil;
  820. NSString *currentNamespace = nil;
  821. switch (i) {
  822. case RCNTestRCInstanceSecondNamespace:
  823. currentAppName = RCNTestsDefaultFIRAppName;
  824. currentOptions = [self firstAppOptions];
  825. currentNamespace = RCNTestsPerfNamespace;
  826. break;
  827. case RCNTestRCInstanceSecondApp:
  828. currentAppName = RCNTestsSecondFIRAppName;
  829. currentOptions = [self secondAppOptions];
  830. currentNamespace = _namespaceGoogleMobilePlatform;
  831. break;
  832. case RCNTestRCInstanceDefault:
  833. default:
  834. currentAppName = RCNTestsDefaultFIRAppName;
  835. currentOptions = [self firstAppOptions];
  836. currentNamespace = RCNTestsFIRNamespace;
  837. break;
  838. }
  839. NSString *fullyQualifiedNamespace =
  840. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  841. RCNUserDefaultsManager *userDefaultsManager =
  842. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  843. bundleID:[NSBundle mainBundle].bundleIdentifier
  844. namespace:fullyQualifiedNamespace];
  845. userDefaultsManager.lastFetchTime = 10;
  846. FIRRemoteConfig *config =
  847. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  848. FIROptions:currentOptions
  849. namespace:currentNamespace
  850. DBManager:_DBManager
  851. configContent:configContent
  852. analytics:nil]);
  853. _configInstances[i] = config;
  854. RCNConfigSettings *settings =
  855. [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  856. namespace:fullyQualifiedNamespace
  857. firebaseAppName:currentAppName
  858. googleAppID:currentOptions.googleAppID];
  859. // Start the test with the assumption that we have some data that was fetched and activated.
  860. settings.lastETag = @"etag1";
  861. settings.lastETagUpdateTime = 100;
  862. settings.lastApplyTimeInterval = 101;
  863. dispatch_queue_t queue =
  864. dispatch_queue_create([[NSString stringWithFormat:@"testNoStatusFetchQueue: %d", i]
  865. cStringUsingEncoding:NSUTF8StringEncoding],
  866. DISPATCH_QUEUE_SERIAL);
  867. _configFetch[i] = OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  868. DBManager:_DBManager
  869. settings:settings
  870. analytics:nil
  871. experiment:nil
  872. queue:queue
  873. namespace:fullyQualifiedNamespace
  874. options:currentOptions]);
  875. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  876. settings:settings
  877. namespace:fullyQualifiedNamespace
  878. options:currentOptions]);
  879. OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  880. .andDo(^(NSInvocation *invocation) {
  881. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  882. NSError *_Nullable error) = nil;
  883. [invocation getArgument:&handler atIndex:3];
  884. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  885. fetchTypeHeader:@"Base/1"
  886. completionHandler:handler
  887. updateCompletionHandler:nil];
  888. });
  889. _response[i] = @{@"state" : @"NO_CHANGE"};
  890. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  891. _URLResponse[i] =
  892. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  893. statusCode:200
  894. HTTPVersion:nil
  895. headerFields:@{@"etag" : @"etag1"}];
  896. id completionBlock =
  897. [OCMArg invokeBlockWithArgs:_responseData[i], _URLResponse[i], [NSNull null], nil];
  898. OCMStub([_configFetch[i] URLSessionDataTaskWithContent:[OCMArg any]
  899. fetchTypeHeader:@"Base/1"
  900. completionHandler:completionBlock])
  901. .andReturn(nil);
  902. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  903. configContent:configContent
  904. configSettings:settings
  905. configExperiment:nil];
  906. }
  907. // Make the fetch calls for all instances.
  908. NSMutableArray<XCTestExpectation *> *expectations =
  909. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  910. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  911. expectations[i] = [self
  912. expectationWithDescription:
  913. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  914. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  915. // Make sure activate returns false in fetch completion.
  916. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  917. NSError *error) {
  918. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  919. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  920. XCTAssertFalse(changed);
  921. XCTAssertNil(error);
  922. [expectations[i] fulfill];
  923. }];
  924. };
  925. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  926. }
  927. [self waitForExpectationsWithTimeout:_expectationTimeout
  928. handler:^(NSError *error) {
  929. XCTAssertNil(error);
  930. }];
  931. }
  932. - (void)testConfigValueForKey {
  933. NSMutableArray<XCTestExpectation *> *expectations =
  934. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  935. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  936. expectations[i] =
  937. [self expectationWithDescription:
  938. [NSString stringWithFormat:@"Test configValueForKey: method - instance %d", i]];
  939. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  940. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  941. NSError *error) {
  942. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess);
  943. XCTAssertNil(error);
  944. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  945. XCTAssertTrue(changed);
  946. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  947. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  948. NSString *key3 = [NSString stringWithFormat:@"key3-%d", i];
  949. NSString *key7 = [NSString stringWithFormat:@"key7-%d", i];
  950. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  951. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  952. NSString *value3 = [NSString stringWithFormat:@"value3-%d", i];
  953. NSString *value7 = [NSString stringWithFormat:@"value7-%d", i];
  954. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  955. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  956. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  957. XCTAssertEqualObjects([self->_configInstances[i] configValueForKey:key3].stringValue,
  958. value3);
  959. if (i == RCNTestRCInstanceDefault) {
  960. XCTAssertEqualObjects([self->_configInstances[i] configValueForKey:key7].stringValue,
  961. value7);
  962. }
  963. XCTAssertEqualObjects([self->_configInstances[i] configValueForKey:key7].stringValue,
  964. value7);
  965. XCTAssertNotNil([self->_configInstances[i] configValueForKey:nil]);
  966. XCTAssertEqual([self->_configInstances[i] configValueForKey:nil].source,
  967. FIRRemoteConfigSourceStatic);
  968. XCTAssertEqual([self->_configInstances[i] configValueForKey:nil].source,
  969. FIRRemoteConfigSourceStatic);
  970. XCTAssertEqual([self->_configInstances[i] configValueForKey:nil source:-1].source,
  971. FIRRemoteConfigSourceStatic);
  972. [expectations[i] fulfill];
  973. }];
  974. };
  975. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  976. }
  977. [self waitForExpectationsWithTimeout:_expectationTimeout
  978. handler:^(NSError *error) {
  979. XCTAssertNil(error);
  980. }];
  981. }
  982. - (void)testFetchConfigWithDefaultSets {
  983. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  984. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  985. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  986. fetchConfigsExpectation[i] = [self
  987. expectationWithDescription:
  988. [NSString stringWithFormat:@"Test fetch configs with defaults set - instance %d", i]];
  989. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  990. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  991. NSString *key0 = [NSString stringWithFormat:@"key0-%d", i];
  992. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  993. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  994. NSDictionary<NSString *, NSString *> *defaults = @{key1 : @"default key1", key0 : @"value0-0"};
  995. [_configInstances[i] setDefaults:defaults];
  996. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  997. NSError *error) {
  998. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  999. XCTAssertNil(error);
  1000. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, @"default key1");
  1001. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceDefault);
  1002. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1003. XCTAssertTrue(changed);
  1004. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  1005. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceRemote);
  1006. XCTAssertEqualObjects([self->_configInstances[i] defaultValueForKey:key1].stringValue,
  1007. @"default key1");
  1008. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  1009. XCTAssertEqualObjects(self->_configInstances[i][key0].stringValue, @"value0-0");
  1010. XCTAssertNil([self->_configInstances[i] defaultValueForKey:nil]);
  1011. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  1012. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  1013. @"Callback of first successful config "
  1014. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccess.");
  1015. [fetchConfigsExpectation[i] fulfill];
  1016. }];
  1017. };
  1018. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1019. }
  1020. [self waitForExpectationsWithTimeout:_expectationTimeout
  1021. handler:^(NSError *error) {
  1022. XCTAssertNil(error);
  1023. }];
  1024. }
  1025. - (void)testDefaultsSetsOnly {
  1026. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1027. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1028. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  1029. NSString *key3 = [NSString stringWithFormat:@"key3-%d", i];
  1030. NSString *key4 = [NSString stringWithFormat:@"key4-%d", i];
  1031. NSString *key5 = [NSString stringWithFormat:@"key5-%d", i];
  1032. NSString *defaultValue1 = @"default value1";
  1033. NSData *defaultValue2 = [defaultValue1 dataUsingEncoding:NSUTF8StringEncoding];
  1034. NSNumber *defaultValue3 = [NSNumber numberWithFloat:3.1415926];
  1035. NSDate *defaultValue4 = [NSDate date];
  1036. BOOL defaultValue5 = NO;
  1037. NSMutableDictionary<NSString *, id> *defaults = [NSMutableDictionary dictionaryWithDictionary:@{
  1038. key1 : defaultValue1,
  1039. key2 : defaultValue2,
  1040. key3 : defaultValue3,
  1041. key4 : defaultValue4,
  1042. key5 : @(defaultValue5),
  1043. }];
  1044. [_configInstances[i] setDefaults:defaults];
  1045. if (i == RCNTestRCInstanceSecondNamespace) {
  1046. [defaults setObject:@"2860" forKey:@"experience"];
  1047. [_configInstances[i] setDefaults:defaults];
  1048. }
  1049. // Remove objects right away to make sure dispatch_async gets the copy.
  1050. [defaults removeAllObjects];
  1051. FIRRemoteConfig *config = _configInstances[i];
  1052. XCTAssertEqualObjects(config[key1].stringValue, defaultValue1, @"Should support string format");
  1053. XCTAssertEqualObjects(config[key2].dataValue, defaultValue2, @"Should support data format");
  1054. XCTAssertEqual(config[key3].numberValue.longValue, defaultValue3.longValue,
  1055. @"Should support number format");
  1056. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1057. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1058. NSString *strValueOfDate = [dateFormatter stringFromDate:(NSDate *)defaultValue4];
  1059. XCTAssertEqualObjects(
  1060. config[key4].stringValue, strValueOfDate,
  1061. @"Date format can be set as an input from plist, but output coming out of "
  1062. @"defaultConfig as string.");
  1063. XCTAssertEqual(config[key5].boolValue, defaultValue5, @"Should support bool format");
  1064. if (i == RCNTestRCInstanceSecondNamespace) {
  1065. XCTAssertEqualObjects(
  1066. [_configInstances[i] configValueForKey:@"experience"].stringValue, @"2860",
  1067. @"Only default config has the key, must equal to default config value.");
  1068. }
  1069. // Reset default sets
  1070. [_configInstances[i] setDefaults:nil];
  1071. XCTAssertEqual([_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceDefault].count, 0);
  1072. }
  1073. }
  1074. - (void)testSetDefaultsWithNilParams {
  1075. NSMutableArray<XCTestExpectation *> *expectations =
  1076. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1077. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1078. expectations[i] = [self
  1079. expectationWithDescription:
  1080. [NSString stringWithFormat:@"Set defaults no callback expectation - instance %d", i]];
  1081. // Should work when passing nil.
  1082. [_configInstances[i] setDefaults:nil];
  1083. [_configInstances[i] setDefaults:nil];
  1084. dispatch_after(
  1085. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1086. dispatch_get_main_queue(), ^{
  1087. XCTAssertEqual(
  1088. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceDefault].count, 0);
  1089. [expectations[i] fulfill];
  1090. });
  1091. }
  1092. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1093. }
  1094. - (void)testFetchConfigOverwriteDefaultSet {
  1095. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1096. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1097. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1098. fetchConfigsExpectation[i] = [self
  1099. expectationWithDescription:
  1100. [NSString stringWithFormat:@"Test fetch configs with defaults set - instance %d", i]];
  1101. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1102. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  1103. [_configInstances[i] setDefaults:@{key1 : @"default key1"}];
  1104. FIRRemoteConfigValue *value = _configInstances[i][key1];
  1105. XCTAssertEqualObjects(value.stringValue, @"default key1");
  1106. XCTAssertEqual(value.source, FIRRemoteConfigSourceDefault);
  1107. value = _configInstances[i][@"A key doesn't exist"];
  1108. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1109. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1110. NSError *error) {
  1111. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  1112. XCTAssertNil(error);
  1113. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1114. XCTAssertTrue(changed);
  1115. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  1116. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceRemote);
  1117. XCTAssertEqualObjects([self->_configInstances[i] defaultValueForKey:key1].stringValue,
  1118. @"default key1");
  1119. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  1120. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  1121. @"Callback of first successful config "
  1122. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccess.");
  1123. [fetchConfigsExpectation[i] fulfill];
  1124. }];
  1125. };
  1126. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1127. }
  1128. [self waitForExpectationsWithTimeout:_expectationTimeout
  1129. handler:^(NSError *error) {
  1130. XCTAssertNil(error);
  1131. }];
  1132. }
  1133. - (void)testGetConfigValueBySource {
  1134. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1135. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1136. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1137. fetchConfigsExpectation[i] =
  1138. [self expectationWithDescription:
  1139. [NSString stringWithFormat:@"Test get config value by source - instance %d", i]];
  1140. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1141. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  1142. NSDictionary<NSString *, NSString *> *defaults = @{key1 : @"default value1"};
  1143. [_configInstances[i] setDefaults:defaults];
  1144. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1145. NSError *error) {
  1146. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  1147. XCTAssertNil(error);
  1148. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, @"default value1");
  1149. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceDefault);
  1150. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1151. XCTAssertTrue(changed);
  1152. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  1153. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceRemote);
  1154. FIRRemoteConfigValue *value;
  1155. if (i == RCNTestRCInstanceDefault) {
  1156. value = [self->_configInstances[i] configValueForKey:key1
  1157. source:FIRRemoteConfigSourceRemote];
  1158. XCTAssertEqualObjects(value.stringValue, value1);
  1159. value = [self->_configInstances[i] configValueForKey:key1
  1160. source:FIRRemoteConfigSourceDefault];
  1161. XCTAssertEqualObjects(value.stringValue, @"default value1");
  1162. value = [self->_configInstances[i] configValueForKey:key1
  1163. source:FIRRemoteConfigSourceStatic];
  1164. } else {
  1165. value = [self->_configInstances[i] configValueForKey:key1
  1166. source:FIRRemoteConfigSourceRemote];
  1167. XCTAssertEqualObjects(value.stringValue, value1);
  1168. value = [self->_configInstances[i] configValueForKey:key1
  1169. source:FIRRemoteConfigSourceDefault];
  1170. XCTAssertEqualObjects(value.stringValue, @"default value1");
  1171. value = [self->_configInstances[i] configValueForKey:key1
  1172. source:FIRRemoteConfigSourceStatic];
  1173. }
  1174. XCTAssertEqualObjects(value.stringValue, @"");
  1175. XCTAssertEqualObjects(value.numberValue, @(0));
  1176. XCTAssertEqual(value.boolValue, NO);
  1177. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  1178. @"Callback of first successful config "
  1179. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccess.");
  1180. [fetchConfigsExpectation[i] fulfill];
  1181. }];
  1182. };
  1183. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1184. }
  1185. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1186. }
  1187. - (void)testInvalidKeyOrNamespace {
  1188. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1189. FIRRemoteConfigValue *value = [_configInstances[i] configValueForKey:nil];
  1190. XCTAssertNotNil(value);
  1191. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1192. value = [_configInstances[i] configValueForKey:nil];
  1193. XCTAssertNotNil(value);
  1194. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1195. value = [_configInstances[i] configValueForKey:nil source:5];
  1196. XCTAssertNotNil(value);
  1197. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1198. }
  1199. }
  1200. // Remote Config converts UTC times in the plists to local times. This utility function makes it
  1201. // possible to check the times when running the tests in any timezone.
  1202. static NSString *UTCToLocal(NSString *utcTime) {
  1203. // Create a UTC dateFormatter.
  1204. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1205. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1206. [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
  1207. NSDate *date = [dateFormatter dateFromString:utcTime];
  1208. [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
  1209. return [dateFormatter stringFromDate:date];
  1210. }
  1211. // Manage different bundle locations for Swift Package Manager, CocoaPods static, CocoaPods dynamic.
  1212. - (void)setDefaultsFor:(FIRRemoteConfig *)config {
  1213. #if SWIFT_PACKAGE
  1214. NSBundle *bundle = SWIFTPM_MODULE_BUNDLE;
  1215. NSString *plistFile = [bundle pathForResource:@"Defaults-testInfo" ofType:@"plist"];
  1216. #else
  1217. NSBundle *bundle = [NSBundle mainBundle];
  1218. NSString *plistFile = [bundle pathForResource:@"Defaults-testInfo" ofType:@"plist"];
  1219. if (plistFile != nil) {
  1220. [config setDefaultsFromPlistFileName:@"Defaults-testInfo"];
  1221. return;
  1222. }
  1223. // We've linked dynamically and the plist file is in the test's bundle.
  1224. for (bundle in [NSBundle allBundles]) {
  1225. plistFile = [bundle pathForResource:@"Defaults-testInfo" ofType:@"plist"];
  1226. if (plistFile != nil) {
  1227. break;
  1228. }
  1229. }
  1230. #endif
  1231. NSDictionary *defaults = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  1232. [config setDefaults:defaults];
  1233. }
  1234. - (void)testSetDefaultsFromPlist {
  1235. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1236. FIRRemoteConfig *config = _configInstances[i];
  1237. [self setDefaultsFor:config];
  1238. XCTAssertEqualObjects(_configInstances[i][@"lastCheckTime"].stringValue,
  1239. UTCToLocal(@"2016-02-28 18:33:31"));
  1240. XCTAssertEqual(_configInstances[i][@"isPaidUser"].boolValue, YES);
  1241. XCTAssertEqualObjects(_configInstances[i][@"dataValue"].stringValue, @"2.4");
  1242. XCTAssertEqualObjects(_configInstances[i][@"New item"].numberValue, @(2.4));
  1243. XCTAssertEqualObjects(_configInstances[i][@"Languages"].stringValue, @"English");
  1244. XCTAssertEqualObjects(_configInstances[i][@"FileInfo"].stringValue,
  1245. @"To setup default config.");
  1246. XCTAssertEqualObjects(_configInstances[i][@"format"].stringValue, @"key to value.");
  1247. XCTAssertEqualObjects(_configInstances[i][@"arrayValue"].JSONValue,
  1248. ((id) @[ @"foo", @"bar", @"baz" ]));
  1249. XCTAssertEqualObjects(_configInstances[i][@"dictValue"].JSONValue,
  1250. ((id) @{@"foo" : @"foo", @"bar" : @"bar", @"baz" : @"baz"}));
  1251. // If given a wrong file name, the default will not be set and kept as previous results.
  1252. [_configInstances[i] setDefaultsFromPlistFileName:@""];
  1253. XCTAssertEqualObjects(_configInstances[i][@"lastCheckTime"].stringValue,
  1254. UTCToLocal(@"2016-02-28 18:33:31"));
  1255. [_configInstances[i] setDefaultsFromPlistFileName:@"non-existed_file"];
  1256. XCTAssertEqualObjects(_configInstances[i][@"dataValue"].stringValue, @"2.4");
  1257. [_configInstances[i] setDefaultsFromPlistFileName:nil];
  1258. XCTAssertEqualObjects(_configInstances[i][@"New item"].numberValue, @(2.4));
  1259. [_configInstances[i] setDefaultsFromPlistFileName:@""];
  1260. XCTAssertEqualObjects(_configInstances[i][@"Languages"].stringValue, @"English");
  1261. }
  1262. }
  1263. - (void)testAllKeysFromSource {
  1264. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1265. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1266. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1267. fetchConfigsExpectation[i] = [self
  1268. expectationWithDescription:[NSString
  1269. stringWithFormat:@"Test allKeys methods - instance %d", i]];
  1270. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1271. NSString *key0 = [NSString stringWithFormat:@"key0-%d", i];
  1272. NSDictionary<NSString *, NSString *> *defaults = @{key1 : @"default key1", key0 : @"value0-0"};
  1273. [_configInstances[i] setDefaults:defaults];
  1274. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1275. NSError *error) {
  1276. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess);
  1277. XCTAssertNil(error);
  1278. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1279. XCTAssertTrue(changed);
  1280. XCTAssertEqual(
  1281. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceRemote].count, 100);
  1282. XCTAssertEqual(
  1283. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceDefault].count, 2);
  1284. XCTAssertEqual(
  1285. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceStatic].count, 0);
  1286. [fetchConfigsExpectation[i] fulfill];
  1287. }];
  1288. };
  1289. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1290. }
  1291. [self waitForExpectationsWithTimeout:_expectationTimeout
  1292. handler:^(NSError *error) {
  1293. XCTAssertNil(error);
  1294. }];
  1295. }
  1296. - (void)testAllKeysWithPrefix {
  1297. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1298. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1299. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1300. fetchConfigsExpectation[i] = [self
  1301. expectationWithDescription:[NSString
  1302. stringWithFormat:@"Test allKeys methods - instance %d", i]];
  1303. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1304. NSError *error) {
  1305. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess);
  1306. XCTAssertNil(error);
  1307. NSLog(@"Testing _configInstances %d", i);
  1308. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1309. XCTAssertTrue(changed);
  1310. // Test keysWithPrefix: method.
  1311. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@"key1"].count, 12);
  1312. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@"key"].count, 100);
  1313. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@"invalid key"].count, 0);
  1314. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:nil].count, 100);
  1315. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@""].count, 100);
  1316. [fetchConfigsExpectation[i] fulfill];
  1317. }];
  1318. };
  1319. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1320. }
  1321. [self waitForExpectationsWithTimeout:_expectationTimeout
  1322. handler:^(NSError *error) {
  1323. XCTAssertNil(error);
  1324. }];
  1325. }
  1326. /// Test the minimum fetch interval is applied and read back correctly.
  1327. - (void)testSetMinimumFetchIntervalConfigSetting {
  1328. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1329. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1330. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1331. fetchConfigsExpectation[i] = [self
  1332. expectationWithDescription:
  1333. [NSString stringWithFormat:@"Test minimumFetchInterval expectation - instance %d", i]];
  1334. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  1335. settings.minimumFetchInterval = 123;
  1336. [_configInstances[i] setConfigSettings:settings];
  1337. XCTAssertEqual([_configInstances[i] configSettings].minimumFetchInterval, 123);
  1338. FIRRemoteConfigFetchCompletion fetchCompletion =
  1339. ^void(FIRRemoteConfigFetchStatus status, NSError *error) {
  1340. XCTAssertFalse([self->_configInstances[i].settings hasMinimumFetchIntervalElapsed:43200]);
  1341. // Update minimum fetch interval.
  1342. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  1343. settings.minimumFetchInterval = 0;
  1344. [self->_configInstances[i] setConfigSettings:settings];
  1345. XCTAssertEqual([self->_configInstances[i] configSettings].minimumFetchInterval, 0);
  1346. XCTAssertTrue([self->_configInstances[i].settings hasMinimumFetchIntervalElapsed:0]);
  1347. [fetchConfigsExpectation[i] fulfill];
  1348. };
  1349. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1350. }
  1351. [self waitForExpectationsWithTimeout:_expectationTimeout
  1352. handler:^(NSError *error) {
  1353. XCTAssertNil(error);
  1354. }];
  1355. }
  1356. /// Test the fetch timeout is properly set and read back.
  1357. - (void)testSetFetchTimeoutConfigSetting {
  1358. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1359. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  1360. settings.fetchTimeout = 1;
  1361. [_configInstances[i] setConfigSettings:settings];
  1362. XCTAssertEqual([_configInstances[i] configSettings].fetchTimeout, 1);
  1363. NSURLSession *networkSession = [_configFetch[i] currentNetworkSession];
  1364. XCTAssertNotNil(networkSession);
  1365. XCTAssertEqual(networkSession.configuration.timeoutIntervalForResource, 1);
  1366. XCTAssertEqual(networkSession.configuration.timeoutIntervalForRequest, 1);
  1367. }
  1368. }
  1369. - (void)testFetchRequestWithUserPropertiesOnly {
  1370. NSDictionary *userProperties = @{@"user_key" : @"user_value"};
  1371. NSString *req = [_settings nextRequestWithUserProperties:userProperties];
  1372. XCTAssertTrue([req containsString:@"analytics_user_properties:{\"user_key\":\"user_value\"}"]);
  1373. XCTAssertFalse([req containsString:@"first_open_time"]);
  1374. }
  1375. - (void)testFetchRequestWithFirstOpenTimeAndUserProperties {
  1376. NSDictionary *userProperties = @{@"_fot" : @1649116800000, @"user_key" : @"user_value"};
  1377. NSString *req = [_settings nextRequestWithUserProperties:userProperties];
  1378. XCTAssertTrue([req containsString:@"first_open_time:'2022-04-05T00:00:00Z'"]);
  1379. XCTAssertTrue([req containsString:@"analytics_user_properties:{\"user_key\":\"user_value\"}"]);
  1380. }
  1381. - (void)testFetchRequestFirstOpenTimeOnly {
  1382. NSDictionary *userProperties = @{@"_fot" : @1650315600000};
  1383. NSString *req = [_settings nextRequestWithUserProperties:userProperties];
  1384. XCTAssertTrue([req containsString:@"first_open_time:'2022-04-18T21:00:00Z'"]);
  1385. XCTAssertFalse([req containsString:@"analytics_user_properties"]);
  1386. }
  1387. #pragma mark - Public Factory Methods
  1388. - (void)testConfigureConfigWithValidInput {
  1389. // Configure the default app with our options and ensure the Remote Config instance is set up
  1390. // properly.
  1391. if (![FIRApp isDefaultAppConfigured]) {
  1392. XCTAssertNoThrow([FIRApp configureWithOptions:[self firstAppOptions]]);
  1393. }
  1394. XCTAssertNoThrow([FIRRemoteConfig remoteConfig]);
  1395. FIRRemoteConfig *config = [FIRRemoteConfig remoteConfig];
  1396. XCTAssertNotNil(config);
  1397. // Ensure the same instance is returned from the singleton.
  1398. FIRRemoteConfig *sameConfig = [FIRRemoteConfig remoteConfig];
  1399. XCTAssertNotNil(sameConfig);
  1400. XCTAssertEqual(config, sameConfig);
  1401. // Ensure the app name is stored properly.
  1402. XCTAssertEqual([config valueForKey:@"_appName"], kFIRDefaultAppName);
  1403. }
  1404. #pragma mark - Realtime tests
  1405. - (void)testRealtimeAddConfigUpdateListenerWithValidListener {
  1406. NSMutableArray<XCTestExpectation *> *expectations =
  1407. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1408. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1409. expectations[i] = [self
  1410. expectationWithDescription:
  1411. [NSString
  1412. stringWithFormat:@"Test Realtime add listener successfully - instance %d", i]];
  1413. OCMStub([_configRealtime[i] beginRealtimeStream]).andDo(nil);
  1414. id completion = ^void(FIRRemoteConfigUpdate *_Nullable configUpdate, NSError *_Nullable error) {
  1415. if (error != nil) {
  1416. NSLog(@"Callback");
  1417. }
  1418. };
  1419. [_configRealtime[i] addConfigUpdateListener:completion];
  1420. dispatch_after(
  1421. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1422. dispatch_get_main_queue(), ^{
  1423. OCMVerify([self->_configRealtime[i] beginRealtimeStream]);
  1424. OCMVerify([self->_configRealtime[i] addConfigUpdateListener:completion]);
  1425. [expectations[i] fulfill];
  1426. });
  1427. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1428. }
  1429. }
  1430. - (void)testRealtimeAddConfigUpdateListenerWithInvalidListener {
  1431. NSMutableArray<XCTestExpectation *> *expectations =
  1432. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1433. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1434. expectations[i] = [self
  1435. expectationWithDescription:
  1436. [NSString
  1437. stringWithFormat:@"Test Realtime add listener unsuccessfully - instance %d", i]];
  1438. id completion = nil;
  1439. [_configRealtime[i] addConfigUpdateListener:completion];
  1440. dispatch_after(
  1441. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1442. dispatch_get_main_queue(), ^{
  1443. OCMVerify(never(), [self->_configRealtime[i] beginRealtimeStream]);
  1444. [expectations[i] fulfill];
  1445. });
  1446. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1447. }
  1448. }
  1449. - (void)testRemoveRealtimeListener {
  1450. NSMutableArray<XCTestExpectation *> *expectations =
  1451. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1452. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1453. expectations[i] = [self
  1454. expectationWithDescription:
  1455. [NSString
  1456. stringWithFormat:@"Test Realtime remove listeners successfully - instance %d", i]];
  1457. id completion = ^void(FIRRemoteConfigUpdate *_Nullable configUpdate, NSError *_Nullable error) {
  1458. if (error != nil) {
  1459. NSLog(@"Callback");
  1460. }
  1461. };
  1462. OCMStub([_configRealtime[i] beginRealtimeStream]).andDo(nil);
  1463. FIRConfigUpdateListenerRegistration *registration =
  1464. [_configRealtime[i] addConfigUpdateListener:completion];
  1465. [registration remove];
  1466. dispatch_after(
  1467. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1468. dispatch_get_main_queue(), ^{
  1469. OCMVerify([self->_configRealtime[i] addConfigUpdateListener:completion]);
  1470. OCMVerify([self->_configRealtime[i] removeConfigUpdateListener:completion]);
  1471. OCMVerify([self->_configRealtime[i] pauseRealtimeStream]);
  1472. [expectations[i] fulfill];
  1473. });
  1474. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1475. }
  1476. }
  1477. - (void)testRealtimeFetch {
  1478. NSMutableArray<XCTestExpectation *> *expectations =
  1479. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1480. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1481. expectations[i] = [self
  1482. expectationWithDescription:
  1483. [NSString stringWithFormat:@"Test Realtime Autofetch successfully - instance %d", i]];
  1484. OCMStub([_configFetch[i] realtimeFetchConfigWithNoExpirationDuration:1
  1485. completionHandler:OCMOCK_ANY])
  1486. .andDo(nil);
  1487. OCMStub([_configRealtime[i] scheduleFetch:1 targetVersion:1]).andDo(nil);
  1488. [_configRealtime[i] fetchLatestConfig:3 targetVersion:1];
  1489. dispatch_after(
  1490. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1491. dispatch_get_main_queue(), ^{
  1492. OCMVerify([self->_configFetch[i] realtimeFetchConfigWithNoExpirationDuration:1
  1493. completionHandler:OCMOCK_ANY]);
  1494. [expectations[i] fulfill];
  1495. });
  1496. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1497. }
  1498. }
  1499. - (void)testAutofetch {
  1500. NSMutableArray<XCTestExpectation *> *expectations =
  1501. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1502. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1503. expectations[i] = [self
  1504. expectationWithDescription:
  1505. [NSString stringWithFormat:@"Test Realtime Autofetch successfully - instance %d", i]];
  1506. OCMStub([_configRealtime[i] scheduleFetch:1 targetVersion:1]).andDo(nil);
  1507. [_configRealtime[i] autoFetch:1 targetVersion:1];
  1508. dispatch_after(
  1509. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1510. dispatch_get_main_queue(), ^{
  1511. OCMVerify([self->_configRealtime[i] scheduleFetch:1 targetVersion:1]);
  1512. [expectations[i] fulfill];
  1513. });
  1514. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1515. }
  1516. }
  1517. - (void)testAddOnConfigUpdateMethodSuccess {
  1518. NSMutableArray<XCTestExpectation *> *expectations =
  1519. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1520. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1521. expectations[i] = [self
  1522. expectationWithDescription:
  1523. [NSString
  1524. stringWithFormat:@"Test public realtime method successfully - instance %d", i]];
  1525. OCMStub([_configRealtime[i] beginRealtimeStream]).andDo(nil);
  1526. id completion = ^void(FIRRemoteConfigUpdate *_Nullable configUpdate, NSError *_Nullable error) {
  1527. if (error != nil) {
  1528. NSLog(@"Callback");
  1529. }
  1530. };
  1531. [_configInstances[i] addOnConfigUpdateListener:completion];
  1532. dispatch_after(
  1533. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1534. dispatch_get_main_queue(), ^{
  1535. OCMVerify([self->_configRealtime[i] addConfigUpdateListener:completion]);
  1536. [expectations[i] fulfill];
  1537. });
  1538. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1539. }
  1540. }
  1541. - (void)testAddOnConfigUpdateMethodFail {
  1542. NSMutableArray<XCTestExpectation *> *expectations =
  1543. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1544. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1545. expectations[i] = [self
  1546. expectationWithDescription:
  1547. [NSString stringWithFormat:@"Test public realtime method and fails - instance %d", i]];
  1548. id completion = nil;
  1549. [_configInstances[i] addOnConfigUpdateListener:completion];
  1550. dispatch_after(
  1551. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1552. dispatch_get_main_queue(), ^{
  1553. OCMVerify(never(), [self->_configRealtime[i] beginRealtimeStream]);
  1554. [expectations[i] fulfill];
  1555. });
  1556. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1557. }
  1558. }
  1559. - (void)testRealtimeDisabled {
  1560. NSMutableArray<XCTestExpectation *> *expectations =
  1561. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1562. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1563. expectations[i] = [self
  1564. expectationWithDescription:
  1565. [NSString
  1566. stringWithFormat:@"Test isRealtimeDisabled flag and makes it true - instance %d",
  1567. i]];
  1568. OCMStub([_configRealtime[i] pauseRealtimeStream]).andDo(nil);
  1569. NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
  1570. [dictionary setValue:@"true" forKey:@"featureDisabled"];
  1571. [dictionary setValue:@"1" forKey:@"latestTemplateVersionNumber"];
  1572. [_configRealtime[i] evaluateStreamResponse:dictionary error:nil];
  1573. dispatch_after(
  1574. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1575. dispatch_get_main_queue(), ^{
  1576. OCMVerify([self->_configRealtime[i] pauseRealtimeStream]);
  1577. OCMVerify(never(), [self->_configRealtime[i] autoFetch:5 targetVersion:1]);
  1578. [expectations[i] fulfill];
  1579. });
  1580. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1581. }
  1582. }
  1583. - (void)testRealtimeStreamRequestBody {
  1584. NSError *error;
  1585. NSData *requestBody = [_configRealtime[0] createRequestBody];
  1586. NSData *uncompressedRequest = [NSData gul_dataByInflatingGzippedData:requestBody error:&error];
  1587. NSString *strData = [[NSString alloc] initWithData:uncompressedRequest
  1588. encoding:NSUTF8StringEncoding];
  1589. XCTAssertTrue([strData containsString:@"project:'correct_gcm_sender_id'"]);
  1590. XCTAssertTrue([strData containsString:@"namespace:'firebase'"]);
  1591. XCTAssertTrue([strData containsString:@"lastKnownVersionNumber:'0'"]);
  1592. XCTAssertTrue([strData containsString:@"appId:'1:123:ios:123abc'"]);
  1593. XCTAssertTrue([strData containsString:@"sdkVersion:"]);
  1594. XCTAssertTrue([strData containsString:@"appInstanceId:'iid'"]);
  1595. }
  1596. - (void)testFetchAndActivateRolloutsNotifyInterop {
  1597. id mockNotificationCenter = [OCMockObject mockForClass:[NSNotificationCenter class]];
  1598. [[mockNotificationCenter expect] postNotificationName:@"RolloutsStateDidChangeNotification"
  1599. object:[OCMArg any]
  1600. userInfo:[OCMArg any]];
  1601. id mockSubscriber = [OCMockObject mockForProtocol:@protocol(FIRRolloutsStateSubscriber)];
  1602. [[mockSubscriber expect] rolloutsStateDidChange:[OCMArg any]];
  1603. XCTestExpectation *expectation = [self
  1604. expectationWithDescription:[NSString
  1605. stringWithFormat:@"Test rollout update send notification"]];
  1606. XCTAssertEqual(_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  1607. FIRRemoteConfigFetchStatusNoFetchYet);
  1608. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion =
  1609. ^void(FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  1610. XCTAssertEqual(status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote);
  1611. XCTAssertNil(error);
  1612. XCTAssertEqual(self->_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  1613. FIRRemoteConfigFetchStatusSuccess);
  1614. XCTAssertNotNil(self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime);
  1615. XCTAssertGreaterThan(
  1616. self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime.timeIntervalSince1970, 0,
  1617. @"last fetch time interval should be set.");
  1618. [expectation fulfill];
  1619. };
  1620. [_configInstances[RCNTestRCInstanceDefault]
  1621. fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  1622. [self waitForExpectationsWithTimeout:_expectationTimeout
  1623. handler:^(NSError *error) {
  1624. XCTAssertNil(error);
  1625. }];
  1626. }
  1627. #pragma mark - Test Helpers
  1628. - (FIROptions *)firstAppOptions {
  1629. // TODO: Evaluate if we want to hardcode things here instead.
  1630. FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:@"1:123:ios:123abc"
  1631. GCMSenderID:@"correct_gcm_sender_id"];
  1632. options.APIKey = @"AIzaSy-ApiKeyWithValidFormat_0123456789";
  1633. options.projectID = @"abc-xyz-123";
  1634. return options;
  1635. }
  1636. - (FIROptions *)secondAppOptions {
  1637. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  1638. #if SWIFT_PACKAGE
  1639. bundle = SWIFTPM_MODULE_BUNDLE;
  1640. #endif
  1641. NSString *plistPath = [bundle pathForResource:@"SecondApp-GoogleService-Info" ofType:@"plist"];
  1642. FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:plistPath];
  1643. XCTAssertNotNil(options);
  1644. return options;
  1645. }
  1646. @end